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
- First I store the image inside a
productImagestable 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);
}
- 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/pramopro_dpk_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?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire