Laravel 9 Ajax Image Upload Example

Laravel 9 ajax image upload with validation; Through this tutorial, i am going to show you how to upload image using jQuery ajax in laravel 9 with validation.

Upload Image Using jQuery Ajax In Laravel 9

Follow the below given simple steps to upload image using jQuery ajax in laravel 9 apps with validation:

  • Step 1 – Installing Laravel 9 Application
  • Step 2 – Configuring Database Details
  • Step 3 – Creating Model & Migration
  • Step 4 – Create Routes
  • Step 5 – Creating Ajax Image Upload Controller
  • Step 6 – Creating Ajax Image Upload Blade View
  • Step 7 – Implementing jQuery validation Code
  • Step 8 – Start Development Server
  • Step 9 – Run Laravel 9 Ajax Image Upload App On Browser

Step 1 – Installing Laravel 9 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel latest application using the following command:

composer create-project --prefer-dist laravel/laravel LaravelAjaxImageUpload

Step 2 – Configuring Database Details

In step 2, open your downloaded laravel app into any text editor. Then find .env file and configure database detail like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3 – Creating Model & Migration

In step 3, open command prompt and navigate to your project by using the following command:

cd / LaravelAjaxImageUpload

Then create model and migration file by using the following command:

php artisan make:model Image -m

The above command will create two files into your laravel image upload tutorial app, which is located inside the following locations:

  • LaravelAjaxImageUpload/app/Models/Image.php
  • LaravelAjaxImageUpload/database/migrations/create_images_table.php

So, find create_images_table.php file inside LaravelAjaxImageUpload/database/migrations/ directory. Then open this file and add the following code into function up() on this file:

    public function up()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('path');
            $table->timestamps();
        });
    }

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 4 – Create Routes

In step 4, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

<?php

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


/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('ajax-image-upload', [AjaxImageUploadController::class, 'index']);
Route::post('upload-image', [AjaxImageUploadController::class, 'ajaxUpload']);

Step 5 – Creating Ajax Image Upload Controller

In step 5, create image upload controller by using the following command:

php artisan make:controller AjaxImageUploadController

The above command will create AjaxImageUploadController.php file, which is located inside LaravelImageUpload/app/Http/Controllers/ directory.

The following laravel validation rules will validate image file before upload/save into database:

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

So open AjaxImageUploadController.php file and add the following code into it:

<?php

namespace App\Http\Controllers;

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

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

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

        ]);

        $name = $request->file('image')->getClientOriginalName();

        $path = $request->file('image')->store('public/images');


        $save = new Image;

        $save->name = $name;
        $save->path = $path;

        $save->save();

        return response()->json($path);

    }
}

The following single line of code will upload image inside storage/app/public/images directory:

        $path = $request->file('image')->store('public/images');

Step 6 – Creating Ajax Image Upload Blade View

In step 6, create new blade view file that named ajax-image-upload.php inside resources/views directory for image upload form.

Note that, the following ajax code will upload image on laravel controller:

            $.ajax({
                type:'POST',
                url: "{{ url('upload-image')}}",
                data: data,
                cache:false,
                contentType: false,
                processData: false,
                success: (data) => {
                  $('#submit').html('Submit');
                  $("#submit"). attr("disabled", false);
                  alert('Ajax form has been submitted successfully');
                  this.reset();
                },
                error: function(data){
                    console.log(data);
                }
            });

Don’t worry i have already added this code into ajax-image-upload.blade.php file.

So, you can add the following php and html form code into ajax-image-upload.blade.php:

<!DOCTYPE html>
<html>
<head>
  <title>Upload image using ajax in laravel 9 - laratutorials</title>

  <meta name="csrf-token" content="{{ csrf_token() }}">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>

  <style>
    .error{
        color: red;
    }
  </style>

</head>
<body>

<div class="container mt-4">

  <div class="card">

    <div class="card-header text-center font-weight-bold">
      <h2>Upload image using ajax in laravel 9 - Laratutorials.com</h2>
    </div>

    <div class="card-body">
        <form method="POST" enctype="multipart/form-data" id="ajax-image-upload" action="javascript:void(0)" >
                  
            <div class="row">

                <div class="col-md-12">
                    <div class="form-group">
                        <input type="file" name="dimage" placeholder="Choose image" id="dimage">
                    </div>
                </div>
                  
                <div class="col-md-12">
                    <button type="submit" class="btn btn-primary" id="submit">Submit</button>
                </div>
            </div>     
        </form>

    </div>

  </div>
<script type="text/javascript">
     

 $(document).ready(function() {
    $("#ajax-image-upload").validate({
        rules: {  
            dimage:{
                required: true,
                //accept:"jpg,png,jpeg,gif"
            }  
        },
        messages: {
            dimage:{
               required: 'Please select the image!',
               //accept: "Only image type jpg/png/jpeg/gif is allowed"
 
            },
        },
        errorElement : 'div',
        errorLabelContainer: '.errorTxt',
        submitHandler: function(form) {
            $.ajaxSetup({
              headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
              }
            });

          $('#submit').html('Please Wait...');
          $("#submit"). attr("disabled", true);
 
            var data = new FormData(form);
 
            $.ajax({
                type:'POST',
                url: "{{ url('upload-image')}}",
                data: data,
                cache:false,
                contentType: false,
                processData: false,
                success: (data) => {
                  $('#submit').html('Submit');
                  $("#submit"). attr("disabled", false);
                  alert('Image has been uploaded using ajax with jQuery successfully');
                  this.reset();
                },
                error: function(data){
                    console.log(data);
                }
            });
        }      
    });
});
</script>
</div>  
</body>
</html>

Step 7 – Implementing jQuery validation Code

The following jQuery code will display error message in laravel ajax image upload forms if upload invalid image. So do not forget to add the following code along laravel forms fields:

 $(document).ready(function() {
    $("#ajax-image-upload").validate({
        rules: {  
            dimage:{
                required: true,
               // accept:"jpg,png,jpeg,gif"
            }  
        },
        messages: {
            dimage:{
               required: 'Please select the image!',
               //accept: "Only image type jpg/png/jpeg/gif is allowed"
 
            },
        },
    });
});

The above jquery validation error message display code along with each form fields. Don’t worry i have already added this code into ajax-image-upload.blade.php file.

Step 8 – Start Development Server

Finally, open your command prompt again and run the following command to start development server for your laravel ajax image upload with jquery validation application:

php artisan serve

Step 9 – Run Laravel 9 ajax Image Upload with Validation App On Browser

In step 9, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/ajax-image-upload

Note that, in this example, the image will be upload on the following path – storage/app/public/images.

Recommended Laravel Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published.