Laravel-medialibrary: getUrl in Model relation

Created on 24 Nov 2016  路  4Comments  路  Source: spatie/laravel-medialibrary

I need to get image path as json

I use
$products = Product::with('categories','media')->paginate(15);

but this display image file name

how can I use getUrl ?

Most helpful comment

You could also append the image URL to your Product model:

// app/Product.php

namespace App;

...

class Product extends Model
{
    protected $appends = ['image_url'];

    public function getImageUrlAttribute()
    {
        return $this->getFirstMediaUrl('images');
    }
}

All 4 comments

How exactly are you trying to retrieve the url from the media item?

@sebastiandedeyne
using this code:
download 9

but I need media image file url or path instead of file name

Since getUrl is a method鈥攏ot a property鈥攐n the Media model, it won't automatically be appended when serializing the media model to json.

To solve this issue, you could either:

  • Use an external package to handle your model serialization (which is what I'd recommend)
  • Extend the Media model, and add the url to $appends

Example of an extended Media model:

// config/laravel-medialibrary.php

return [
    'media_model' => App\Media::class,
];
// app/Media.php

namespace App;

use Spatie\MediaLibrary\Media as BaseMedia;

class Media extends BaseMedia
{
    protected $appends = ['url'];

    public function getUrlAttribute(): string
    {
        return $this->getUrl();
    }
}

If you're interested in more advanced model serialization, check out our laravel-fractal package: https://github.com/spatie/laravel-fractal

You could also append the image URL to your Product model:

// app/Product.php

namespace App;

...

class Product extends Model
{
    protected $appends = ['image_url'];

    public function getImageUrlAttribute()
    {
        return $this->getFirstMediaUrl('images');
    }
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

xron89 picture xron89  路  3Comments

Radiergummi picture Radiergummi  路  4Comments

swash13 picture swash13  路  3Comments

eichgi picture eichgi  路  3Comments

brendt picture brendt  路  4Comments