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
Dear AndrewBNZ thank you for your repay
my problem is not with loop becouse
return User::all();
return User::all()->item;
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.
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.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community