Lafoune
Lafoune

Reputation: 486

Laravel: Invalid argument supplied for foreach()

I get data from looping in station_id to get data from the schedule.

$stations_id = Station::pluck('id'); // Output [1,2,3,4]
$schedules = [];
foreach ($stations_id as $station_id) {
     echo $schedules = Schedule::select('id')
                        ->where('station_id', $station_id)
                        ->latest()
                        ->first();                
     }

The echo of $schedules output is:

{"id":16}{"id":17}{"id":15}

But the issue is here, I have tried to loop through $schedules to get a data from another table called Queue, I mean I want to get latest queues of every schedule we are looping in it.

So I did it like this:

$queues = [];
foreach ($schedules as $schedule) {       
    echo $queues = Queue::withTrashed()
                 ->latest()
                 ->where('schedule_id', $schedule);               
}

but it showed this error:

Invalid argument supplied for foreach()

I didn't know where I missed it.

Upvotes: 0

Views: 745

Answers (1)

Adam Rodriguez
Adam Rodriguez

Reputation: 1856

The variable $schedules isn't an array when you finish your first loop. You'll want $schedules to be an array after your first loop:

$stations_id = Station::pluck('id'); // Output [1,2,3,4]
$schedules = [];
foreach ($stations_id as $station_id) {
     $schedules[] = Schedule::select('id')
                    ->where('station_id', $station_id)
                    ->latest()
                    ->first();                
}

// second loop here

$queues = [];
foreach ($schedules as $schedule) {       
    $queues[] = Queue::withTrashed()
             ->latest()
             ->where('schedule_id', $schedule->getKey())->first();               
}

// do something with queues

Upvotes: 2

Related Questions