vendredi 11 octobre 2019

laravel can not access to relation attributes

I have model product as follow:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    //

    public function Category(){
        return $this->belongsTo('App\Category');
    }
    public function size_unit(){
        return $this->belongsTo('App\size_unit', 'size_unit');
    }
}

the size_units table have two columns: id, unit the product table have size_unit column which is foreign key that reference the id on size_units table

when I try to access unit column for product using:


I get the following error:

"Trying to get property 'unit' of non-object"

but when I use:


I can see the unit under relation -> attributes, so I tried to use:

$product->size_unit()->unit

I get the following error:

"Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$unit"

i am fetching the product using with('size_unit)

please tell me what is wrong and how to fix it?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire