Shaddow
Shaddow

Reputation: 3215

Get property of relation in model

class Ingredient extends Eloquent {

    public function unit() {
        return $this->hasOne('IngredientUnit', 'id', 'unit_id');
    }

}

class IngredientUnit extends Eloquent {

    public function ingredient() {
        return $this->belongsTo('Ingredient', 'unit_id', 'id');
    }

    public function getNamesAttribute() {
        $quantity = $this->ingredient()->quantity; // <- ErrorException

        ...
    }

}

ErrorException (E_UNKNOWN):

Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$quantity

If I remove brackets - $this->ingredient->quantity; - I get

ErrorException (E_UNKNOWN)

Trying to get property of non-object

How can I get property of relation object (belongsTo) ?


Schemas:

    Schema::create('ingredients', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('recipe_id')->unsigned();
        $table->integer('unit_id')->unsigned()->nullable();
        $table->float('quantity')->unsigned();
        ...
    });

    Schema::create('ingredient_units', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('name');
        ...
    });

Upvotes: 0

Views: 6449

Answers (2)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

With these tables your relations are wrong.

You need to swap them, for it goes like this: unit hasOne/hasMany ingredients, ingredient belongsTo unit.

// Ingredient
public function unit() 
{
    return $this->belongsTo('IngredientUnit', 'unit_id', 'id');
}

// IngredientUnit - I don't think it's hasOne, rather hasMany
public function ingredients() 
{
    return $this->hasMany('Ingredient', 'unit_id', 'id');
}

Next, this can't work:

$this->ingredient()->quantity;

but this will work, as long as there is model returned from the relation:

$this->ingredient->quantity;

So basically you don't have related ingredient, that's why it returns null and your get the error.

Upvotes: 3

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111899

First you should change:

$quantity = $this->ingredient()->quantity;

into

$quantity = $this->ingredient->quantity;

But in case no Ingredient is found, you get exception, so you should better change it into:

$ingredient = $this->ingredient;
$quantity = ($ingredient) ? $ingredient->quantity : 0;

to assign 0 if no ingredient is found;

Upvotes: 0

Related Questions