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 Downgrade PHP 8 to 7.4 in Ubuntu
How To Downgrade PHP 8 to 7.4...

As a web developer, I understand the significance of embracing the latest technologies to stay ahead in the dynamic worl...

Read More

Aug-04-2023

How to Create Payment Link in Stripe using API in Laravel 10
How to Create Payment Link in...

In today's digital age, the ability to facilitate online payments efficiently is crucial for businesses and develope...

Read More

Oct-09-2023

Bootstrap Modal In Angular 13
Bootstrap Modal In Angular 13

In this article, we will see the bootstrap modal in angular 13. Ng Bootstrap is developed from bootstrap and they p...

Read More

Jun-10-2022

Laravel tips: DB Models and Eloquent - Part 2
Laravel tips: DB Models and El...

Laravel, the PHP web application framework, is renowned for its elegant and efficient approach to handling databases thr...

Read More

Oct-13-2023