0

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

Farshad
  • 1,286
  • 1
  • 21
  • 37
  • Make `$room_price` an array. Right now you are doing `$room_price =` which is assignment and would override the previous value. – nice_dev Nov 07 '19 at 14:04
  • Create an array, store data by calling add item inside the loop. – Asif Raza Nov 07 '19 at 14:07
  • Possible duplicate of [How to add a new item inside an array](https://stackoverflow.com/questions/14253613/how-to-add-a-new-item-inside-an-array) – Asif Raza Nov 07 '19 at 14:09
  • Also, this isn't an efficient way to retrieve data. What is the query trying to do with `from_date` and `to_date`? – nice_dev Nov 07 '19 at 14:17
  • @vivek_23 yes its like `->whereDate('from_date', '=', $dates[$i])` without `to_date` – Y JRB Nov 07 '19 at 14:21
  • @YJRB Doesn't like because he has the sign of `<=` and `>=`. I am finding it hard to make sense from that query. – nice_dev Nov 07 '19 at 14:31

2 Answers2

0

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);
Y JRB
  • 301
  • 2
  • 12
0

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');

} }