Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel / Cannot access protected property Illuminate\Database\Eloquent\Collection::$items

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?

like image 666
Eben Hafkamp Avatar asked May 02 '16 10:05

Eben Hafkamp


1 Answers

$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;

like image 111
Filip Koblański Avatar answered Oct 17 '22 05:10

Filip Koblański