Laravel 8 Ajax Image Upload Example
Tags: laravel, javascript, ajax
Published: 2022-04-19 06:14:42

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/laravel-8-ajax-image-upload-example

In this post, I will share an example of how to upload an image in Laravel 8 using ajax. In my previous post, I posted about [Laravel image upload without ajax](https://codeanddeploy.com/blog/laravel/tutorial-for-laravel-8-image-upload-example). Now let's do the ajax function so that our page will not need to reload after submitting the request to our server.

![ajax-laravel-8-image](https://ecn-storage.s3.us-west-2.amazonaws.com/articles/ajax-laravel-8-image-upload-example-TgfTanKhSax980.webp?ctm=1633015133)

![ajax-laravel-8](https://ecn-storage.s3.us-west-2.amazonaws.com/articles/ajax-laravel-8-image-upload-example-kBl0xtlPxNx980.webp?ctm=1633015160)


To make it short just use my previous tutorial about [Laravel image upload](https://codeanddeploy.com/blog/laravel/tutorial-for-laravel-8-image-upload-example) then integrate the ajax.

 

Okay, let's start I assume that you already followed my previous tutorial.

 

## Step 1: Update our Controller Code for Laravel Ajax Image Upload

Below code is our updated code to support the Laravel ajax image upload.


```php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\ImageUploadRequest;

class ImageUploadController extends Controller
{
    public function index() 
    {
        return view('image-upload.index');
    }

    public function upload(ImageUploadRequest $request) 
    {

        $filename = time() . '.' . $request->image->extension();

        $request->image->move(public_path('images'), $filename);

        // save uploaded image filename here to your database

        return response()->json([
            'message' => 'Image uploaded successfully.',
           'image' => 'images/' . $filename
        ], 200);
    }
}
```

## Step 2: Update for View

Now let's update our view code to support the ajax functionality. See below code:

```php
<!DOCTYPE html>
    <html>

    <head>
        <meta charset="utf-8" />
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Laravel 8 Image Upload Example - codeanddeploy.com</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>

        <style type="text/css">
            .error {
                color: red
            }

            #image {
                display: none;
            }
        </style>

        <script type="text/javascript">
            $(document).ready(function(){
              $('#laravel-image-upload').on('submit', function(event){
                    event.preventDefault();

                    var url = $('#laravel-image-upload').attr('data-action');

                    $.ajax({
                        url: url,
                        method: 'POST',
                        data: new FormData(this),
                        dataType: 'JSON',
                        contentType: false,
                        cache: false,
                        processData: false,
                        success:function(response)
                        {
                            $('#image').attr('src', response.image).show();

                            alert(response.message)
                        },
                        error: function(response) {
                            $('.error').remove();
                            $.each(response.responseJSON.errors, function(k, v) {
                                $('[name=\"image\"]').after('<p class="error">'+v[0]+'</p>');
                            });
                        }
                    });
                });

            });
        </script>
    </head>

    <body>
        <div class="container mt-5">
            <img width="200px" id="image">

            <form data-action="{{ route('image-upload.post') }}" method="POST" enctype="multipart/form-data" id="laravel-image-upload">
                @csrf
                <div class="row">
        
                    <div class="col-md-6">
                        <input type="file" name="image" class="form-control">
                    </div>
         
                    <div class="col-md-6">
                        <button type="submit" class="btn btn-success">Upload</button>
                    </div>
         
                </div>
            </form>
        </div>
    </body>
</html>
```

Now you have an idea already how to do the Laravel 8 image upload using ajax. I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-8-ajax-image-upload-example if you want to download this code.

Happy coding :)