Image upload or file upload is a little bit difficult if you want to upload it using Ajax request. Without Ajax request, it is very easy to upload images in the Laravel application. But uploading images using Ajax requests gives us great UI and performance. Cause you already know, using Ajax request, we can upload images without form submission as well as without page refresh.

In this tutorial, I will show you how to upload images using Ajax in laravel 10 application. I will create this upload image in laravel 10 using the Ajax tutorial step by step so that you can catch it easily. I will create a Image model and table to save this image dynamically to test our tutorial on how to upload image using jquery in laravel.

We do not need to use any multi-part form data for uploading images using ajax requests. To upload an image using the ajax request, we can convert it into base 64 or we can upload an image without converting base 64 by just reading the file and passing it with the ajax request. So let's see laravel 10 ajax file upload.

laravel-10-ajax-image-upload

Step 1: Download Fresh Laravel 10

In the first step of how to upload file with ajax in laravel, download a fresh Laravel application by the following command:

composer create-project laravel/laravel example-app

 

Step 2:  Create Route

Now in this step, create a route like the one below to complete the how to upload image in laravel ajax. I am going to use an Ajax controller. So we can create this laravel 10 ajax file upload.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImageController;

Route::get('photo', [ImageController::class, 'index']);
Route::get('photo', [HttpController::class, 'save']);

 

Step 3: Create Controller

Now we have to create ImageController to complete our how to upload image using jquery in laravel. So run the below command to create a controller:

php artisan make:controller ImageController

 

Now update this controller like this:

app/Http/Controllers/ImageController.php

<?php

namespace App\Http\Controllers;

use App\Models\Image;
use Illuminate\Http\Request;

class ImageController extends Controller
{
    public function index()
    {
        return view('welcome');
    }

    public function save(Request $request)
    {
        request()->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        if ($files = $request->file('image')) {
            $fileName =  "image-" . time() . '.' . $request->image->getClientOriginalExtension();
            $request->image->storeAs('image', $fileName);

            $image = new Image;
            $image->image = $fileName;
            $image->save();

            return response()->json(["image" => $fileName]);
        }
    }
}

 

Step 4 Create Views

Now in this final step, we have to create our welcome.blade.php. so create it and paste this below code.

resources/views/welcome.blade.php

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Laravel 10 Ajax Image Upload</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>

<body>
    <div class="container mt-4">
        <div class="row">
            <div class="col-sm-12">
                <h4>Upload image using ajax with preview</h4>
            </div>
        </div>
        <hr />
        <form method="POST" enctype="multipart/form-data" id="upload_image_form" action="javascript:void(0)">
            <div class="row">
                <div class="col-md-12 mb-2">
                    <img id="image_preview_container" src="{{ asset('storage/image/image-preview.png') }}"
                        alt="preview image" style="max-height: 150px;">
                </div>
                <div class="col-md-12">
                    <div class="form-group">
                        <input type="file" name="image" placeholder="Choose image" id="image">
                        <span class="text-danger">{{ $errors->first('title') }}</span>
                    </div>
                </div>
                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary">Submit</button>
                </div>
            </div>
        </form>
    </div>
    <script>
        $(document).ready(function(e) {
            $('#image').change(function() {
                let reader = new FileReader();
                reader.onload = (e) => {
                    $('#image_preview_container').attr('src', e.target.result);
                }
                reader.readAsDataURL(this.files[0]);
            });
            $('#upload_image_form').submit(function(e) {
                e.preventDefault();
                var formData = new FormData(this);
                $.ajax({
                    type: 'POST',
                    url: "{{ url('photo') }}",
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                    success: (data) => {
                        this.reset();
                    },
                    error: function(data) {
                        console.log(data);
                    }
                });
            });
        });
    </script>
</body>
</html>

 

Now run this below command to symlink storage public to the public directory like that:

php artisan storage:link

 

Read also: How To Show Data In Modal Using AJAX In Laravel?

 

Conclusion

Now we know how to upload image in laravel 10 using ajax. Hope after completing this how to upload the image using Ajax in laravel tutorial, you can able to upload image or any file using ajax request.