Reputation: 1653
I have a one-to-many relationship defined in Laravel:
TheModules
has many TheModulesActions
and TheModulesActions
has one TheModules
.
It works well, however I would like to set a custom attribute inside TheModulesActions
called url
.
To achieve that I need the following code:
protected $appends = array('url');
public function getUrlAttribute() {
$nameURL = SharedMethods::slugify($this->title);
$url = "#/control/{$module}/{$nameURL}/{$this->id}";
return $url;
}
Till now everything works, however $module
variable is empty, all I have is $this->moduleID
which is linked to TheModules
.
I need $this->TheModules()->title
but it doesn't work inside my getUrlAttribute
method.
Is there any way to access relationship data inside getAttribute
?
The Relationships in TheModulesActions
class are:
public function TheModule() {
return $this->belongsTo('App\TheModules');
}
The Relationships in TheModules
class are:
public function TheActions() {
return $this->hasMany('App\TheModulesActions', 'moduleID');
}
Tried $this->TheModules->title
:
Gives me this error:
ErrorException in TheModulesActions.php line 15: Trying to get property of non-object
Upvotes: 0
Views: 1361
Reputation: 17668
You can it by dropping the parenthesis ()
on the relation name as:
$this->TheModules->title
When you use parenthesis with relation name then Laravel returns an instance of query builder.
Upvotes: 2