Laravel Relationships: Trying to get property 'name' of non-object

Viewed 183

I hope someone can please help me here because this is doing my head in.

I have two models, Ingredient and Uom (unit of measure).

In Ingredient I have:

public function uom() {
    return $this->belongsTo(Uom::class, 'uom');
}

Each ingredient will have only one unit of measure. The column uom in the database is the one that holds the id for the unit of measure.

In Uom I have:

public function ingredients() {
    return $this->hasMany(Ingredient::class);
}

Each unit of measure could have many ingredients.

In the ingredients table migration I have set up the foreign key as follows:

$table->foreign('uom')->references('id')->on('uoms')->onDelete('cascade');

Could someone please tell me why in the below foreach I get

Trying to get property 'name' of non-object 

The blade code:

@foreach ($ingredients as $ingredient)
    <tr>
        <td>{{$ingredient->name}}</td>
        <td>{{$ingredient->uom->name}}</td>
        <td>{{$ingredient->user->name}}</td>
    </tr>
@endforeach

The $ingredient->user->name works perfectly referencing a column 'added_by' so I'm at a loss as to why uom doesn't work.

Thanks in advance for any help, I hope I'm just overlooking something stupid

1 Answers

The problem you have is that the attribute has the same name as the relationship method you have: uom. If you change the column name on the ingredients from uom to uom_id, and change the relationship method in the model so the line states the following:

public function uom() {
    return $this->belongsTo(Uom::class);
}

This should fix your problem (plus the relationship works like Laravel is intended to work)

Laraval has two options: return the relationship (the uom method) or the attribute (which is an integer from the database). Apparently it returns the integer which isn't an object and thus has no method name.

Related