How to upload multiple images in Laravel 8 with validations

Uploading multiple images in Laravel 8 can be a complex process, but with the right knowledge, it can be accomplished easily. In this article, we’ll guide you through a step-by-step process on how to upload multiple images in Laravel 8 with all validations.

Step 1: Create the View for Uploading Images

The first step is to create a view for the form that will allow the user to upload multiple images. We will use Laravel’s Blade templating engine to create the view. Here’s a basic view for uploading multiple images:

<form method="post" action="{{ route('images.store') }}" enctype="multipart/form-data">    @csrf    <div class="form-group">        <label for="images">Choose Images:</label>        <input type="file" name="images[]" multiple class="form-control-file" id="images">    </div>    <button type="submit" class="btn btn-primary">Upload</button></form>

Note that the form has the enctype="multipart/form-data" attribute, which is required when uploading files in a form.

Step 2: Create the Controller

Next, we will create a controller that will handle the image upload. We will use Laravel’s make:controller command to generate a new controller. In your terminal, navigate to the root directory of your Laravel application and run the following command:

php artisan make:controller ImageController --resource

This will generate a new controller file in the app/Http/Controllers directory with the name ImageController.php. The --resource option creates a controller with all the necessary CRUD methods.

Open the ImageController.php file and add the following code to the store method:

public function store(Request $request){    $request->validate([        'images' => 'required',        'images.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'    ]);    if($request->hasfile('images'))    {        foreach($request->file('images') as $image)        {            $name = time().'_'.$image->getClientOriginalName();            $image->move(public_path().'/images/', $name);              $data[] = $name;          }    }    return response()->json(['success'=>'Images uploaded successfully']);}

In the code above, we first validate the images input field using Laravel’s built-in validation. We require the images field to be present and each image file to be an image of type jpeg, png, jpg, gif, svg, and no larger than 2MB.

Next, we check if the images input field has any files using the hasfile method. If files are present, we loop through each file and save it to the public/images directory with a unique name generated using the current timestamp and the original file name.

Finally, we return a JSON response with a success message.

Step 3: Create the Route

Next, we need to create a route that will point to the store method in the ImageController. Open the web.php file located in the routes directory and add the following route:

Route::post('/images', [ImageController::class, 'store'])->name('images.store');

Step 4: Test the Image Upload

Now we are ready to test the image upload functionality. Start the Laravel development server by running the following command in your terminal:

php artisan serve

Navigate to the URL of your Laravel application and click on the link to the view for uploading images that we created earlier. Choose multiple images using the file input field and click on the “Upload” button.

If the images are valid and the upload is successful, you should see a success message in JSON format. You can also check the public/images directory to confirm that the images were saved successfully.

Congratulations, you have successfully implemented an image upload functionality in Laravel 8 with all the necessary validations. You can now customize this functionality to suit your specific requirements.

Comments