Unable to use Foreach loop with results of DB::Table

I'm unable to wrap my head around why I'm getting "Cannot use object of type stdClass as array" error messages when trying to loop through the results of a DB query. Been scouring the interwebs for how to properly use this and haven't been able to get it to work.

In a controller, I have something like this...

$data = [];
$data['foo'] = 'bar';
$data['something'] = 'somethingelse';
$data['items'] = DB::table('items')->get();
return view('home',$data);

Then in the view:

@foreach($items as $item)

This gives me: "Cannot use object of type stdClass as array". Works fine if I do something like:

$data['items'] = Item::all();

but in this case I need to use DB. Any thoughts? Not sure what I'm missing here... Thanks.

dracola replied 1 week ago Solution

When you use DB('table_name')->get() it returns a Collection that means it is a Class you should use $item->name instead of $item['name']

But if you want keep use array syntax then change this line:

$data['items'] = DB::table('items')->get();

to be:

$data['items'] = DB::table('items')->get()->toArray() // Or ->all();
Luke Ramus replied 1 week ago

Got it, thanks for the clarification.

Sign in to participate in this thread!

We'd like to thank these amazing companies for supporting us