Laravel getRelations () returns empty

I am trying to query a relationship to use with an accessory using getNameAttribute this is my code

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Conference extends Model{

    public function getNameAttribute() {
        return $this->getRelation('event')->name;
    }

    public function event() {
        return $this->belongsTo('App\Event');
    }

    public function speakers() {
        return $this->hasMany('App\Speaker');
    }
}

      

But that doesn't return anything. Am I doing something wrong? Thank!

+3


source to share


2 answers


At the time you ask for a relationship event

, that relationship has not yet been loaded, so you get an empty value. If you want to access a relation event

, just do this $this->event

, it will load it so you can access its properties:

public function getNameAttribute() {
    return $this->event->name;
}

      



getRelation

the method will return the relation to you, if it has already been loaded into the model, it will not initiate loading.

+2


source


You want to use instead getRelationValue

.

public function getNameAttribute() {
    return $this->getRelationValue('event')->name;
}

      



This method will load the relationship if it has not already been loaded.

+1


source







All Articles