简体   繁体   中英

how to store data in a variable using elequent in a for loop laravel

i have a for loop that i am using a query in it, but when i try to get the data it only shows me the last time that query have been running like below:

 for ($i = 0; $i < count($dates); $i++) {

            for ($f = 0; $f < count($room_ids); $f++) {

                /****************************************
                 * Looping for the Number of Rooms User Given
                 *****************************************/
                $room_price = RoomPrice::with('Room')
                    ->where('room_id', $room_ids[$f])
                    ->whereDate('from_date', '<=', $dates[$i])
                    ->whereDate('to_date', '>=', $dates[$i])
                    ->get()->sortBy('created_at');
}
}

how can i store $room_price so i can have all the data that every time query runned will be stored in a collection or something. thanks

Initiate a new collection (outside the loops)

$room_prices = collect();

Every time you loop and get your $room_price you push it to $room_prices

$room_price->push($room_prices);

You can use.= to store the data till end the loop. Check below code. for ($i = 0; $i < count($dates); $i++) {

        for ($f = 0; $f < count($room_ids); $f++) {

            /****************************************
             * Looping for the Number of Rooms User Given
             *****************************************/
            $room_price .= RoomPrice::with('Room')
                ->where('room_id', $room_ids[$f])
                ->whereDate('from_date', '<=', $dates[$i])
                ->whereDate('to_date', '>=', $dates[$i])
                ->get()->sortBy('created_at');

} }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM