How to Upload Image using AJAX in Laravel 11

In this guide, we'll see how to upload images using AJAX in laravel 11. Here, we'll learn about the process of uploading images using AJAX in Laravel 11. Also, you can upload images without refreshing the page.

In this example, I'll guide you through creating an "images" table with a "name" column. We'll also make a form with a file input. When you submit it, we'll use a jQuery AJAX request to send the image, storing it in both a folder and the database.

Laravel 11 Image Upload using AJAX

how_to_upload_image_using_ajax_in_laravel_11

Step 1: Install Laravel 11

 In the first step, we'll install laravel using the following composer command.

composer create-project laravel/laravel laravel-11-example

 

 

Step 2: Create Migration and Model

Then, we'll create a migration for the Images table. So, run the following command.

php artisan make:migration create_images_table

Migration:

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists('images');
    }
};

Next, run the following command to migrate the migration to the database.

php artisan migrate

Then, we'll create an Image model using the following command.

php artisan make:model Image

app/Models/Image.php

<?php
    
namespace App\Models;
    
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
    
class Image extends Model
{
    use HasFactory;
    
    protected $fillable = [
        'name'
    ];
}

 

Step 3: Create Controller

We'll create an ImageController and define the index() and store() functions.

php artisan make:controller ImageController

app/Http/Controllers/ImageController.php

<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Models\Image;
use Illuminate\View\View;
use Illuminate\Http\JsonResponse;
    
class ImageController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(): View
    {
        return view('image-upload');
    }
          
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg|max:4096'
        ]);
            
        $image_name = time().'.'.$request->image->extension();  
             
        $request->image->move(public_path('images'), $image_name);
          
        Image::create(['name' => $image_name]);
  
        return response()->json(['success' => 'Images uploaded successfully!']);
    }
}

Store Images in Public Folder

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

Store Images in Storage Folder

$image->storeAs('images', $image_name);
 
Step 4: Create Routes

Next, we'll define routes in the web.php file. Add the following routes to that file:

routes/web.php

<?php
   
use Illuminate\Support\Facades\Route;
   
use App\Http\Controllers\ImageController;
   
Route::get('image-upload', [ImageController::class, 'index']);
Route::post('image-upload', [ImageController::class, 'store'])->name('image.store');
 

 

Step 5: Create Blade File

Then, we'll create an image-upload.blade.php file and add a form with the input file. Also, we'll define the AJAX call for image upload.

resources/views/image-upload.blade.php

<!DOCTYPE html>
<html>
	<head>
		<title>How to Upload Image using AJAX in Laravel 11 - Techsolutionstuff</title>
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
		<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
		<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
	</head>
	<body>
		<div class="container">
			<div class="card mt-5">
				<h3 class="card-header p-3"><i class="fa fa-star"></i> How to Upload Image using AJAX in Laravel 11 - Techsolutionstuff</h3>
				<div class="card-body">
					<img id="preview-image" width="300px">
					<form action="{{ route('image.store') }}" method="POST" enctype="multipart/form-data" class="mt-2" id="image-upload">
						@csrf
						<div class="alert alert-danger print-error-msg" style="display:none">
							<ul></ul>
						</div>
						<div class="mb-3">
							<label class="form-label" for="input-image">Select Image:</label>
							<input type="file" name="image" id="input-image" multiple class="form-control @error('images') is-invalid @enderror">
							@error('images')
							<span class="text-danger">{{ $message }}</span>
							@enderror
						</div>
						<div class="mb-3">
							<button type="submit" class="btn btn-success"><i class="fa fa-save"></i> Upload</button>
						</div>
					</form>
				</div>
			</div>
		</div>
	</body>
	<script type="text/javascript">
		$('#input-image').change(function(){    
		    let reader = new FileReader();
		   
		    reader.onload = (e) => { 
		        $('#preview-image').attr('src', e.target.result); 
		    }   
		    
		    reader.readAsDataURL(this.files[0]); 
		     
		});
		    
		$('#image-upload').submit(function(e) {
		       e.preventDefault();
		       let formData = new FormData(this);
		       $('#image-input-error').text('');
		  
		       $.ajax({
		            type:'POST',
		            url: "{{ route('image.store') }}",
		            data: formData,
		            contentType: false,
		            processData: false,
		            success: (response) => {
		                this.reset();
		                console.log('Image has been uploaded successfully');
		            },
		            error: function(response){
		                $('#image-upload').find(".print-error-msg").find("ul").html('');
		                $('#image-upload').find(".print-error-msg").css('display','block');
		                $.each( response.responseJSON.errors, function( key, value ) {
		                    $('#image-upload').find(".print-error-msg").find("ul").append('<li>'+value+'</li>');
		                });
		            }
		       });
		});
		      
	</script>
</html>

 

Step 6: Run the Laravel 11 App

In the last step, execute the following command to start the Laravel development server.

php artisan serve

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS