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 ?
How exactly are you trying to retrieve the url from the media item?
@sebastiandedeyne
using this code:

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:
Media model, and add the url to $appendsExample 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');
}
}
Most helpful comment
You could also append the image URL to your Product model: