phpreactjslaravelinertiajs

How to show public images on Laravel 11 with Inertia and React


I'm uploading images via a form using Laravel 11 and React with Inertia, the images are being stored here C:\wamp64\www\ecommerce\storage\app\public\product_images. (I'm using Windows).

For example:

C:\wamp64\www\ecommerce\storage\app\public\product_images\gibson-lp-classic-20240717001924.png

I've been trying to show a small thumbnail of the image on the edit page, but it just doesn't show:

<div className="mt-4">
  {images.map((image, index) => (
    <div
      key={image.id || index}
      className="flex items-center justify-between mb-2"
    >
      <div className="flex items-center">
        <img
          src={
            image.url ||
            (image instanceof File || image instanceof Blob
              ? URL.createObjectURL(image)
              : '')
          }
          alt={image.name || 'Image'}
          className="w-16 h-16 object-cover mr-4"
        />
      </div>
      <button
        type="button"
        className="text-red-500 hover:text-red-700 focus:outline-none"
        onClick={() => handleImageRemove(index)}
      >
        Delete
      </button>
    </div>
  ))}
</div>
{errors.length > 0 && (
  <div className="mt-4 text-red-600">
    {errors.map((error, index) => (
      <div key={index}>{error}</div>
    ))}
  </div>
)}

I want to show the images that are already stored, but can't seem to access any image via the browser or through react, the filesystems.php is intact, I haven't touched it.

What can I try next?


Solution

  • Laravel uses a symbolic link to access the files in the storage/app/public directory via the public/storage URL. Ensure you have created this symbolic link by running the following Artisan command:

    php artisan storage:link

    Then you can send the url to your component with Inertia, just change the below to suit your application.

    $product = Product::find($id);
    $imagePath = asset('storage/product_images/' . $product->image_url);
    
    return Inertia::render('Product/Edit', [
      'product' => $product,
      'imagePath' => $imagePath,
    ]);
    

    Then output in React:

    {imagePath && (
      <div>
        <img src={imagePath} alt={product.name} />
      </div>
    )}