How to Upload Image in Laravel 10 using AJAX

Laravel is a popular PHP framework that makes it easy to build web applications. In this tutorial, we'll walk you through the process of uploading images in Laravel 10 using AJAX. Image uploads are a common feature in web applications, and doing it asynchronously with AJAX can enhance user experience.

In this tutorial, we'll explore how to harness the power of Laravel 10 to implement image uploads, and we'll take it a step further by doing it asynchronously using AJAX (Asynchronous JavaScript and XML).

This approach not only streamlines the user experience but also adds a touch of modernity to your application.

By the end of this guide, you'll have a clear understanding of how to create an image upload system in Laravel 10.

Step 1: Set Up a Laravel Project

If you haven't already, create a new Laravel project or use an existing one. You can do this by running the following command

composer create-project --prefer-dist laravel/laravel laravel-10-ajax-image-upload

 

Step 2: Create Migration and Model

You'll need a table to store information about the uploaded images. Open your command line terminal and run the following command to create a migration.

php artisan make:migration create_images_table

This will create a new migration file in the database/migrations directory.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

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

    public function down()
    {
        Schema::dropIfExists('images');
    }
}

Run the migration to create the images table by running.

php artisan migrate

Create a Model

Now, create a model that corresponds to the images table. Run the following command.

php artisan make:model Image

This will create an Image.php file in the app/Models directory.

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Image extends Model
{
    use HasFactory;

    protected $table = 'images';
  
    protected $fillable = [
        'name'
    ];
}

 

 

Step 3: Set Up the Controller

Create a controller that handles image uploads. Run the following command to generate a controller.

php artisan make:controller ImageController

In the ImageController.php file, add the following code to handle image uploads.

<?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,svg|max:2048',
        ]);
        
        $imageName = time().'.'.$request->image->extension();  
         
        $request->image->move(public_path('images'), $imageName);
      
        Image::create(['name' => $imageName]);
        
        return response()->json('Image uploaded successfully');
    }
}

 

Step 4: Define Routes

In your web.php file, define a route for handling image uploads.

<?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('image-upload', 'index');
    Route::post('image-upload', 'store')->name('image.store');
});

 

Step 5: Set Up AJAX for Image Upload

Create a JavaScript file to handle the AJAX request for image upload. Here's an example using jQuery.

resources/views/image-upload.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to Upload Image in Laravel 10 using AJAX - Techsolutionstuff</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
<div class="container">
    <div class="panel panel-primary card mt-5">
        <div class="panel-heading text-center mt-4">
            <h2>How to Upload Image in Laravel 10 using AJAX - Techsolutionstuff</h2>
        </div>
        <div class="panel-body card-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 the Laravel Development Server

Start the Laravel development server by running the following command.

php artisan serve

 

Conclusion

In this tutorial, we've covered how to upload images in Laravel 10 using AJAX. Users can now select and upload images asynchronously, enhancing the user experience of your web application.

 


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