I'm still learning Laravel and I'm using eloquent to run my queries. In my application a user can belong to one circle. The circle contains repositories, which in turn contains items. I am trying to fetch all of the items which belong to various repositories within one circle.
User Model:
public function circle () {
return $this->belongsTo('App\Models\Circle');
}
Circle Model:
public function users () {
return $this->hasMany('App\Models\User');
}
public function repositories () {
return $this->hasMany('App\Models\Repository');
}
Repository Model:
public function items () {
return $this->hasMany('App\Models\Item');
}
public function circle () {
return $this->belongsTo('App\Models\Circle');
}
Item Model:
public function repository () {
return $this->belongsTo('App\Models\Repository');
}
Here is the markup where I am trying to iterate over all items:
@foreach($items as $item)
<span>{{ $item->name }}</span>
@endforeach
My controller responsible for handling the route is here:
function library () {
$user = Auth::user();
$circle = $user->circle;
$repositories = $circle->repositories;
$items = $repositories->items;
return View('pages.library', compact(['user', 'circle', 'items']));
}
As of right now I can retrieve 2 repositories belonging to a circle but I cannot retrieve the multiple items that belong to those 2 repositories. I have tried a @foreach on the repositories to run through both and push the items in an empty array but I only end up with the last item. Is there a query technique/step that I'm missing?
$repositories
is a collection not a model. So you shouldn't call the $items
property prom it because it's protected.
I know that You looking for the items relation so... You need to itterate over the $repositories
and the over the each $repository
$item like:
@foreach($repositories as $repository)
@foreach($repository->items as $item)
<span>{{ $item->name }}</span>
@endforeach
@endforeach
And remove this from the controller:
$items = $repositories->items;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With