Sajjad
Sajjad

Reputation: 1615

Accessor for relation objects in Laravel

this is my Category model:

/**
 * @var array
 */
protected $guarded = ['id'];


public function media()
{
    return $this->belongsTo(Media::class);
}

public function getMediaAttribute()
{
    return 'Foo';

    return ( ! is_null($this->media))
        ? $this->media
        : '/products/default/thumb.jpg';
}

and when i call it in route for get all object like this:

return \App\Category::with('media')->get();

it seems accessor not work and i can't get 'Foo' in category's media object

Upvotes: 0

Views: 2297

Answers (2)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

You can use withDefault():

public function media()
{
    return $this->belongsTo(Media::class)
        ->withDefault(['url' => '/products/default/thumb.jpg']);
}

When there is no result, it returns a Media instance with the given attributes.

Upvotes: 2

bestestefan
bestestefan

Reputation: 871

that's not how laravel accessors work

if you created it like

public function getMediaAttribute()
{
    return 'Foo';

    return ( ! is_null($this->media))
        ? $this->media
        : '/products/default/thumb.jpg';
}

then you will access it like:

return \App\Category::first()->media;

it will work as 'additional field' which can be manipulated in various ways for your model, in this case for the model category

more info on that: https://laravel.com/docs/5.6/eloquent-mutators#defining-an-accessor

also as mentioned in the comment under your question, accessor with the same name as the relationship will override original field with given name, I'm not 100% sure the last part about overriding, that's how it works with mutators, I think it's same with accessors

Upvotes: -1

Related Questions