Laravel-medialibrary: How to return image URL via an API

Created on 2 May 2018  路  4Comments  路  Source: spatie/laravel-medialibrary

Hello, all the example i have seen which used this Laravel package used it with Laravel blade views. I was wondering if it is possible to return an image url as a relationship like the way it is below.
return Product::with("product_image")->get()

Most helpful comment

An other option is to use API Resource or laravel fractal, for API resource I will something like:

//app/Http/Resources/ProductResource.php

class ProductResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
           'image' => $this->media->getFullUrl(),
           ...
    }
}

And in your controller:

$product = Product::with("product_image")->get();
return new ProductResource($product);

All 4 comments

Add $with = ['media']; to the Product model and create your own Media model (extending the default media model) and add $appends = ['url'] with a getUrlAttribute method.

Docs:

An other option is to use API Resource or laravel fractal, for API resource I will something like:

//app/Http/Resources/ProductResource.php

class ProductResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
           'image' => $this->media->getFullUrl(),
           ...
    }
}

And in your controller:

$product = Product::with("product_image")->get();
return new ProductResource($product);

Thanks for explaining two excellent options @bhulsman and @rachid804 馃憤

Thanks for explaining two excellent options @bhulsman and @rachid804

I am facing the same issue please I still do not understand what to do. Can you please help break it down in more simpler terms as I am new to API resources and all. Thanks

Was this page helpful?
0 / 5 - 0 ratings

Related issues

brendt picture brendt  路  4Comments

jam1e picture jam1e  路  3Comments

netanelwebninja picture netanelwebninja  路  3Comments

intrepidws picture intrepidws  路  3Comments

amrnn90 picture amrnn90  路  3Comments