2
votes

I am trying to loop through an array of ids to get data from another table, I mean I want to get latest queues of every schedule id we are looping in it.

So first i have $schedules:

$schedules = [{"id":19},{"id":18},{"id":15}]

And the foreach loop is like this:

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

when i return queues it's showing :

Object of class Illuminate\Database\Eloquent\Builder could not be converted to string

2
you are defining $queueses = []; and then you are using $queues[] = Queue::.... Is this a typo? Also, you are not running the query, you need a ->get() at the end of Queue::...->where(...)->get()porloscerros Ψ
thanks man, but i have another problem of getting only empty square brackets, and when i remove ->where('schedule_id', $schedule) this will work but is getting data that i dont want. what is wrong with that line of code @porloscerrosΨLafoune
try with ->where('schedule_id', $schedule->id);porloscerros Ψ
umm, i dont think this will work, it just gotten worse, it's saying Trying to get property 'id' of non-object. is that suppose to appear? @porloscerrosΨLafoune
if you are defining the variable $schedules and assigning it the value as it is shown in the question, try doing it this way: $schedules = json_decode('[{"id":19},{"id":18},{"id":15}]');porloscerros Ψ

2 Answers

5
votes

The error that shows is related to you are not running the query, you need a ->get() at the end of Queue::...->where(...)->get() to do it.

if you dont do it, as Dhananjay Kyada say in his answer:

it will try to return a query object

But to return a response:

The Response content must be a string or object implementing __toString()

Next, we need to tackle one more thing.

If you are defining the variable $schedules and assigning it the value as it is shown in the question:

$schedules = [{"id":19},{"id":18},{"id":15}]

try to do it taking the JSON as string and converting it into a PHP variable with json_decode:

$schedules = json_decode('[{"id":19},{"id":18},{"id":15}]');

Then you can use the id values in you where clause:

->where('schedule_id', $schedule->id)->get()
2
votes

Maybe because you are not getting the result from your query. Because it is just a query it will return a query object. You need to add ->get() in order to get the result. You can try the following code:

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