vendredi 11 décembre 2015

Trouble getting attribute of relation in Laravel

I'm having a trouble with a relation in Laravel 5. the thing is that I have a table User and that user belongs to a Group for that, in the User model I have this:

public function group(){
    return $this->belongsTo('App\models\Group');
}

The model Group have this attributes: name,unity,level, init_date. I also put there a default function to return a group as String, this is the code:

public function __toString(){
        return $this->name.' Unity '.$this->unity;
    }

So, the thing that in a view a have many users and for each of them I want to display the unity, name,date. When I call $user->group it returns me correctly the name and the unity in a String (because the _toString function) that means that he is really querying the group perfectly, but then, when I want to access a simple attribute as unity,date,or name with $user->group->name Laravel gives me this error:

Trying to get property of non-object

I even tried $user->group()->name then I gets: Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire