Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Call to a member function toArray() on array Error

Tags:

php

macos

laravel

I was hoping someone could possibly clear up a little confusion I've been having with this Error. So here is my code. (note) the User model has a hasMany relationship to Image

    $user = User::with('profile')->whereUsername($username)->firstOrFail();

    $images = $user->images->all();

    dd($user->toArray());

My confusion is dd($user->toArray()); works perfectly fine. But when I try this dd($images->toArray()) I get a Call to a member function toArray() on array. This has been killing me for a while. $user and $images are both objects but toArray() only works on $user. Also, $images[0]->toArray() works fine too so that just adds to the confusion.

like image 614
technoY2K Avatar asked Oct 23 '14 20:10

technoY2K


1 Answers

I think this happens because $images is a collection of objects not an object like $user. Check querying-relations in the documentation the red area in the end of that section. That explains why $images[0]->toArray() works fine.

like image 119
geoandri Avatar answered Oct 13 '22 20:10

geoandri