Skip to content
Advertisement

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 AppCategory::with('media')->get();

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement