How to use a relationship in Laravel Accessor
Categorized as Laravel
Imagine, you have to use a relation within your Model Accessor. Let’s see our Post Model example:
// Appending the Accessor name
protected $appends = ['seo_title'];
// The Relationship
public function platform()
{
return $this->belongsTo(Platform::class)->withDefault();
}
// The Accessor
protected function seoTitle(): Attribute {
return Attribute::make(
get: function ($value, $attributes) {
if (!empty($attributes['payment_id'])) {
if ($attributes['payment_id'] == 2) {
$value = 'Online course '.$attributes['title'].' by '.$this->platform->name;
} else {
$value = 'Free online course '.$attributes['title'].' by '.$this->platform->name;
}
} else {
$value = $attributes['title'];
}
return $value;
}
);
}
As you see, we reference the relation with this code – $this->platform->name
. Don’t forget that you have to “camel case” seoTitle
for your accessor method name, and use it as a “snake case” seo_title
in your Blade file or in the Controller.
In your Blade file:
{{ $post->seo_title }}
The Model Accessors make the developer’s life so easy! Enjoy