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
Two Way Data Binding In Angular 12
Two Way Data Binding In Angula...

In this article, we will see how two-way data binding in angular 12. When you create a variable or property to data...

Read More

May-12-2022

How to Validate Empty Input Field in jQuery
How to Validate Empty Input Fi...

In the dynamic world of web development, form validation is a crucial aspect of creating a user-friendly and error-free...

Read More

Sep-25-2023

File Upload With Progress Bar In Angular 13
File Upload With Progress Bar...

In this article, we will see the file upload with a progress bar in angular 13. In this example, we will learn how to im...

Read More

Jun-11-2022

Create Dummy Data Using Laravel Tinker
Create Dummy Data Using Larave...

In this example we can see how to add multiple dummy records in the database at a time using tinker and factory, mo...

Read More

May-21-2020