Search code examples
phplaraveleloquentlaravel-5.3

get items from 'with' in eloquent query and display to blade


So i have this eloquent query

$categories = categories::all();
foreach($categories as $c):
    $c->items = item_categories::where('cat_id',$c->cat_id)->with('item')->with('item.item_images')->get();
endforeach;

and in my blade, I can display this part

with('item')

like doing

@foreach($categories as $c)
    @foreach($c->items as $i)
        {{ $i->item->item_name }}
    @endforeach
@endforeach

How about retrieving data from this part?

with('item.item_images')

I tried

@foreach($categories as $c)
    @foreach($c->items as $i)
        {{ $i->item->item->item_images->image_name }}
    @endforeach
@endforeach

but it gives me error

Trying to get property of non-object

Any ideas, help please?

here's the 'categories' model

class categories extends Model
{
    protected $table = 'categories';
    protected $primaryKey = 'cat_id';

    public function item_category(){
        return $this->belongsTo('App\item_categories','cat_id','cat_id');
    }

}

and the 'item_categories' model

class item_categories extends Model{

    protected $table = "item_categories";

    public function item(){
        return $this->belongsTo('App\items','item_id','item_id');
    }
    public function category(){
        return $this->hasOne('App\categories','cat_id','cat_id');
    }
}

and the 'items' model

class items extends Model
{
    protected $table = 'items';
    protected $primaryKey = 'item_id';

    public function item_images(){
        return $this->hasMany('App\item_images','item_id','item_id');
    }
    public function item_categories(){
        return $this->hasMany('App\item_categories','item_id','item_id');
    }
}

Solution

  • You're going too deep. It looks like item_categories has an item, which has an item_image, so you just need to access it like this:

    {{ $i->item->item_images->image_name }}
    

    Since each item has many item_images, you need to iterate through it.

    @foreach($i->item->item_images as $image)
         {{$image->image_name}}
    @endforeach