Search code examples
laravellaravel-bladelaravel-5.3

Laravel blade one-to-one relationship in @foreach loop


I have a problem with show one to one relationship in Laravel.

I have that tables in DB: manufacturers with defaul Laravel id column and cashregisters with manufacturer_id column releated to id from manufacturers table.

In models I do that:

Cashregister

class Cashregister extends Model
{
    protected $table = "cashregisters";

    public function manufacturer(){

        return $this->hasOne('App\Manufacturer','id');

    }
}

Manufacturer

class Manufacturer extends Model
{
    protected $table = "manufacturers";

    public function cashregisters(){

        return $this->belongsTo('App\Cashregister');

    }
}

I think this is ok. Next I do in CashregisterController that in index():

$cashregisters = Cashregister::all();
return view('cashregisters.index')->withCashregisters($cashregisters);

In cashregisters index View i do that loop:

    <tbody>
    @foreach ($cashregisters as $cashregister)
    <tr>
    <th>{{ $cashregister->id }}</th>
    <td>{{ $cashregister->manufacturer_id }}</td>
                         ......
    <td>{{ $cashregister->DataNastPrzegUrzFisk }}</td>
    @endforeach
    </tr>
    </tbody>

And it works great. Show everything from cashregisters table.

I want to display Manufacturer name instead of manufacturer_id, so I try do this that:

 <td>{{ $cashregister->manufacturer->name }}</td>

Bu I got an error.

Next I searchover internet and try do that thing

@foreach ($cashregisters as $cashregister)
        <tr>
        <th>{{ $cashregister->id }}</th>
      @foreach ($cashregister->manufacturer() as $item)
        <td>{{ $item->name}}</td>
      @endforeach
                             ......
        <td>{{ $cashregister->DataNastPrzegUrzFisk }}</td>
        @endforeach
        </tr>
        </tbody>

But this piece of code show nothing :( Can anyone help me to fix that. When I after all table do that code:

<td>{{ $cashregister->manufacturer->name}}</td>

it show some information, so I think relationship is ok.


Solution

  • You need to set local key for manufacturer, like this:

        class Cashregister extends Model
    {
        protected $table = "cashregisters";
    
        public function manufacturer(){
    
            return $this->hasOne('App\Manufacturer','id', 'manufacturer_id');
    
        }
    }