Reputation: 2478
I have created a model relationship between 3 different tables/models.
Since I get a collection of objects due to hasMany-property I have to use a for-loop to access each of the Models methods in order to get the data I want. Is there anyway to tell that I want it to run the same function on all the objects?
Pseudo code:
Model A //HasMany Model B
Model B //HasMany Model C, Belongs to A
Model C //BelongsTo C
$foo = new User::Find(Auth::id());
//Need to loop the collection of data in order to get the information
foreach($foo->permissions as $permission)
{
$name = $permission->permissionsTypes->name;
}
I have tried to do this:
$foo->permissions->permissionsTypes;
But since it is a collection it does not work.
Is there any other way to get this information without looping through the array?
Thanks for any guidance!
Upvotes: 1
Views: 653
Reputation: 25906
Use pluck()
and collapse()
:
$permissionsTypes = $foo->permissions->pluck('permissionsTypes')->collapse();
Upvotes: 1
Reputation: 941
Might be you have defined the hasMany relationship if yes then please change hasMany into hasOne then
foreach($foo->permissions as $permission)
{
$name = $permission->permissionsTypes->name;
}
Or you could just get one of objects by it's index:
{{ $permission[0]->name}}
Or get first object from collection:
{{ $permission->first() }}
When you're using find()
or first()
you get an object, so you can get properties with simple:
{{ $object->name}}
Upvotes: 0