Lets say I have an Attribute Model like this:
class Attribute extends Model
{
public function group()
{
return $this->belongsTo(Group::class);
}
}
And a Group Model like this:
class Group extends Model
{
public function attributes()
{
return $this->hasMany(Attribute::class);
}
}
So there's One To Many relationship between these two Models and every attribute has a group_id
which is stored at the DB:
And I'm printing attributes at Blade like this:
Controller:
public function index()
{
$attributes = Attribute::all();
return view('admin.attributes.index', compact(['attributes']));
}
Now I want to know how to access the attributes()
function at Group Model when using a foreach loop of all $attributes
.
For example, here is my Blade:
@foreach($attributes as $attribute)
@php
$groupInfo = \App\Models\Attribute\Group::where('id',$attribute->group_id)->first();
$groupAttrs = $groupInfo->attributes;
@endphp
@foreach($groupAttrs as $gr_attr)
{{ $gr_attr->name }}
@endforeach
@endforeach
So in this way, I can correctly access all the attributes that a group id is referenced with.
But I did this by calling the Model directly in the Blade and used @php ... @endphp
. So this is NOT a good way.
So how can I access the Object related Model inversely and print data from it properly ?