Table of contents

ajax laravel image upload

In this post, I will share an example of how to upload an image in Laravel 9 using ajax. In my previous post, I posted about Laravel image upload without ajax. Now let's do the ajax function so that our page will not need to reload after submitting the request to our server.

 

laravel ajax image upload

 

laravel ajax image upload

To make it short just use my previous tutorial about Laravel image upload 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

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 the below code:

<!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 9 image upload using ajax. I hope it helps. Thank you for visiting :)