简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM