Mena
Mena

Reputation: 2029

Return image path in Laravel API resource

I am build a laravel 5.8 API only application and want to return the image path as path of an API resource so that it can be consumed inside an image source attribute. So this is what I have to done to achieve this. 1. I ran php artisan storgae:link command to create the symbolic link from public/storage to storage/app/public

  1. First I store the image inside a productImages table when a new product is successfully created like this
public function store(Request $request)
{
    // create & store the product
    if ($product = Product::create([
        'name'      => $request->name,
        'category'  => $request->category,
        'status'    => $request->status,
        'price'     => $request->price,
        'interest'  => $request->interest,
    ])) {
        // store the product image
        $file = $request->file('image');
        $destinationPath = "public/images/products";
        $filename = 'pramopro_' . $product->name . '_' . $product->id . '.' . $file->extension();

        Storage::putFileAs($destinationPath, $file, $filename);

        ProductImage::create([
            'product_id'    => $product->id,
            'name'          => $filename
        ]);
    }

    // return new product
    return new ProductResource($product);
}
  1. Return the image path in the ProductResource like this
public function toArray($request)
{
    return [
        'id'        => $this->id,
        'name'      => $this->name,
        'category'  => $this->category,
        'status'    => $this->status,
        'price'     => $this->price,
        'interest'  => $this->interest,
        'hidden'    => $this->hidden,
        'imageUrl'  => asset('images/products/' . $this->image->name)
    ];
}

Testing it on my local serve I get a path like this

{
    "id": 1,
    "name": "dpk",
    "category": "fuel",
    "status": "open",
    "price": 100000,
    "interest": 0.2,
    "hidden": 0,
    "imageUrl": "http://localhost:8000/images/products/pramopro_dpk_1.jpeg"
  }

When I try to view the image by putting http://localhost:8000/images/products/randomtext_1.jpeg in my browser, I get 404 not found error.

But this http://localhost:8000/storage/images/products/pramopro_dpk_1.jpeg displays the image as expected.

How should I be retrieving the image path for it to work?

Upvotes: 0

Views: 5633

Answers (1)

Rabie Shishko
Rabie Shishko

Reputation: 56

the asset() function puts you in your public directory, you need to add /storage to the path of your file , try this in your toArray function

'imageUrl'  => asset('storage/images/products/' . $this->image->name)

Personal note , handling media in laravel can be a headache i personally use LaravelMediaLibrary by spaite

https://github.com/spatie/laravel-medialibrary

it has really helped me and made handling media as easy as it can get especially when handling multiple media for the same model

Upvotes: 3

Related Questions