Laravel E-Commerce Project

Laravel 8 E-Commerce - Add Product Gallery


Video Thumbnail

In this video, we will learn how to add a product gallery image to our e-commerce application.

Let's explore how to add multiple images as a product gallery for a single product.

Switch to your project and open the AdminAddProductComponent view file.

Inside this file, after the product image, add the following code for the product gallery:


<div class=`form-group`>
	<label class=`col-md-4 control-label`>Product Gallery</label>
	<div class=`col-md-4`>
		<input type=`file` class=`input-file` wire:model=`images` multiple />
		@if($images)
			@foreach($images as $image)
				<img src=`{{$image->temporaryUrl()}}` width=`120` />
			@endforeach
		@endif  
		@error('images')  <p class=`text-danger`>{{$message}}</p> @enderror                                    
	</div>
</div>    

Next, go to the AdminAddProductComponent class file.

Add a property for the image gallery by writing the following code:


public $images;

Inside the addProduct method, add the following code:


if($this->images)
{
	$imagesname = '';
	foreach($this->images as $key=>$image)
	{
		$imgName = Carbon::now()->timestamp. $key. '.' . $image->extension();
		$image->storeAs('products',$imgName);
		$imagesname = $imagesname . ',' . $imgName;
	}
	$product->images = $imagesname;
}

Now, let's display these gallery images on the product details page.

Go to the product details page and find the div with the class product-gallery.

Add the following code to display the gallery images:


<div class=`detail-media`>
	<div class=`product-gallery` wire:ignore>
		<ul class=`slides`>
			<li data-thumb=`{{ asset('assets/images/products' ) }}/{{$product->image}}`>
				<img src=`{{ asset('assets/images/products') }}/{{$product->image}}` alt=`{{$product->name}}` />
			</li> 
			@php 
				$images = explode(`,`,$product->images);
			@endphp     
			@foreach($images as $image)
				@if($image)
					<li data-thumb=`{{ asset('assets/images/products' ) }}/{{$image}}`>
						<img src=`{{ asset('assets/images/products') }}/{{$image}}` alt=`{{$product->name}}` />
					</li> 
				@endif
			@endforeach                          
		</ul>
	</div>
</div>

That's it! Let's check the result.

Switch to your browser and refresh the page.

Create a new product with a product image and product gallery images.

After adding the product, check the product details page.

You should see the product with an image gallery.

And that's how you can add a product image gallery to your e-commerce application.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.