How To Image Upload Using Ajax In Laravel 9

Websolutionstuff | Feb-07-2023 | Categories : Laravel PHP jQuery

In this article, we will see how to image upload using ajax in laravel 9. Here, we will learn about image upload in laravel 7, laravel 8, and laravel 9 using jquery ajax. So, you can upload an image without page refresh in laravel 8 and laravel 9.

So, let's see laravel 9 image upload using ajax, upload image in laravel 8 using ajax, and image upload with ajax in laravel 8 and laravel 9.

For this example, we will create a migration and model. So, we will store the image in the database using jquery ajax call in laravel 9.

Laravel 9 Upload Image Using AJAX

 

Step 1: Install Laravel 9

In this step, we will install the laravel 9 application using the following command.

composer create-project laravel/laravel laravel-9-ajax-image-upload

 

Step 2: Create Migration and Model

Now, we will create a model and migration using 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()
    {
        Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('images');
    }
};

After that, we will migrate the image table to the database using the following command.

php artisan migrate

Now, we will create an Image model using the below 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 ImageController

In this step, we will create ImageController using the following command.

php artisan make:controller ImageController

app/Http/Controllers/ImageController.php

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

In this step, we will create routes in the web.php file.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ImageController;
  
/* 
|--------------------------------------------------------------------------
| 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::controller(ImageController::class)->group(function(){
    Route::get('upload-image', 'index');
    Route::post('upload-image', 'store')->name('image.store');
});

 

Step 5: Create Blade File

Now, we will create an image_upload.blade.php file. So, add the below code to that file.

resources/views/image_upload.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How To Image Upload Using Ajax In Laravel 9 - Websolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
       
<body>
<div class="container">
         
    <div class="panel panel-primary">
    
      <div class="panel-heading">
        <h2>How To Image Upload Using Ajax In Laravel 9 - Websolutionstuff</h2>
      </div>
   
      <div class="panel-body">
         
        <img id="preview-image" width="300px">
       
        <form action="{{ route('image.store') }}" method="POST" id="image-upload" enctype="multipart/form-data">
            @csrf
    
            <div class="mb-3">
                <label class="form-label" for="inputImage">Image:</label>
                <input 
                    type="file" 
                    name="image" 
                    id="inputImage"
                    class="form-control">
                <span class="text-danger" id="image-input-error"></span>
            </div>
     
            <div class="mb-3">
                <button type="submit" class="btn btn-success">Upload</button>
            </div>
        
        </form>
        
      </div>
    </div>
</div>
</body>
  
<script type="text/javascript">
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
  
    $('#inputImage').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) => {
                 if (response) {
                   this.reset();
                   alert('Image has been uploaded successfully');
                 }
               },
               error: function(response){
                    $('#image-input-error').text(response.responseJSON.message);
               }
           });
    });
      
</script>
      
</html>

 

 

Step 6: Run Laravel 9 Application

Now, we will laravel 9 image upload using jquery ajax using the following command.

php artisan serve

 


You might also like:

Recommended Post
Featured Post
How to Create Artisan Command in Laravel with Arguments Support?
How to Create Artisan Command...

Laravel is a comprehensive framework that provides an extensive range of artisan commands, enabling the automation of di...

Read More

Oct-06-2023

How To Add Date Range Picker In Angular 15 Material
How To Add Date Range Picker I...

In this tutorial, I will guide you through the process of adding a date range picker component to your Angular 15 applic...

Read More

Jun-30-2023

Github And Git Commands
Github And Git Commands

GitHub, Inc. is a United States-based global company that provides hosting for software development and version control...

Read More

Jul-15-2020

How To Create Zip File In Laravel 7/8
How To Create Zip File In Lara...

In this tutorial I will give you example of how to create zip file in laravel 7/8. Some times client's have requirme...

Read More

Dec-17-2021