Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

As the error says, you're trying to get a relationship on a collection, the relationship exists on the objects (records) in that collection. You need to loop over the Users, and for each one get their items...

$users = User::all();

// Blade template
@foreach ($users as $user)
  // access user properties here
  @foreach ($user->item as $item)
    // access item properties here.
  @endforeach
@endforeach
Last updated 2 years ago.
0

Dear AndrewBNZ thank you for your repay

my problem is not with loop becouse

this is work

     return  User::all();

this is not work

      return  User::all()->item;
Last updated 2 years ago.
0

Yes, it is your problem. You can't access the relationship like that - all() gives you back a collection, a list, a bucket of records - relationships need to be retrieved on each individual record, not the collection.

Last updated 2 years ago.
0

AndrewBNZ is right, all() will return a collection but since you used hasMany under User class in Item, you really need to loop it to be able to retrieve the record.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

hsm61 hsm61 Joined 10 Apr 2014

Moderators

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

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.