Sigal Zahavi
Sigal Zahavi

Reputation: 1063

Relationship does not display related fields Laravel

Using Laravel 5.4

I have 2 tables: origins and coffees.

The relations between them:

In Coffee model:

public function origin()
{
   return $this->belongsTo('App\Origin');
}

In the Origin model:

 public function coffee()
{
   return $this->hasMany('App\Coffee');
}

In my controller I have this method:

$origins = Origin::with(['coffee' => function ($query) {
            $query->where('active', 1);
            $query->orderBy('name', 'asc');
        }])->orderBy('name', 'asc')->get();

In my view:

@foreach($origins as $origin)
    {{ $origin->name }}
    <pre>{{ $origin->coffee->name }}</pre>
@endforeach

I get this error:

Property [name] does not exist on this collection instance.

If I code:

@foreach($origins as $origin)
        {{ $origin->name }}
        <pre>{{ $origin->coffee }}</pre>
    @endforeach

I get all the coffees that belong to the origin.

What am I doing wrong?

Upvotes: 0

Views: 25

Answers (1)

Hieu Le
Hieu Le

Reputation: 8415

$origin->coffee is a collection, not a single object. Your models also tell us that one Origin model has many Coffee models.

To list all coffees in the current origin:

@foreach($origins as $origin)
    {{ $origin->name }}

    @foreach($origin->coffee as $coffee)
    <pre>{{ $coffee->name }}</pre>
    @endforeach
@endforeach

Upvotes: 1

Related Questions