How to Upload Image using Ajax in Laravel 9?

10-Apr-2023

.

Admin

How to Upload Image using Ajax in Laravel 9?

Hi friends,

Today, I am going to show you simple example of how to upload image using ajax in laravel 9?. In this tutorial you can find how to upload image or file on folder by using Ajax in Laravel 9 Framework. In this article we explain how to upload image in laravel 9 using ajax jquery Example Tutorial from scratch in step by step. This example explain you Laravel 9 – Ajax Image Upload Example Tutorial step by step guide. More then times we need to save the image data with ajax request in laravel 9 app without page reload and refresh. In this laravel 9 jquery ajax Image upload tutorial i will show you how to upload image using ajax request. Also we will see how to validate the image before uploading it into server.

If you know laravel form submit using ajax then uploading image in laravel using ajax and save in database it too easy. Call the store method with the path at which you wish to store the uploaded file.

We can upload image using Ajax request in laravel 9 very easily. Let's start our laravel 9 ajax image upload tutorial from scratch.

Step 1: Download Laravel


Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app

Step 2: Add Migration and Model

Here, we will create migration for "images" table, let's run bellow command and update code.

php artisan make:migration create_images_table

2022_02_23_054554_create_images_table.php

<?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');

}

};

Next, run create new migration using laravel migration command as bellow:

php artisan migrate

Now we will create Image model by using following 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 $table = 'images';

protected $fillable = [

'name'

];

}

Step 3: Add Controller

In this step, we will create a new ImageUploadController; in this file, we will add two method index() and store() for render view and store images into folder and database logic.

Let's create ImageUploadController by following command:

php artisan make:controller ImageUploadController

next, let's update the following code to Controller File.

app/Http/Controllers/ImageUploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Image;

class ImageUploadController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

return view('imageUpload');

}

/**

* 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',

]);

$imageName = time().'.'.$request->image->extension();

$request->image->move(public_path('images'), $imageName);

Image::create(['name' => $imageName]);

return response()->json('Image uploaded successfully');

}

}

Store Images in Storage Folder

$image->storeAs('images', $imageName);

// storage/app/images/file.png

Store Images in Public Folder

$image->move(public_path('images'), $imageName);

// public/images/file.png

Store Images in S3

$image->storeAs('images', $imageName, 's3');

Step 4: Add Routes

Furthermore, open routes/web.php file and add the routes to manage GET and POST requests for render view and store image logic.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\ImageUploadController;

/*

|--------------------------------------------------------------------------

| 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(ImageUploadController::class)->group(function(){

Route::get('image-upload', 'index');

Route::post('image-upload', 'store')->name('image.store');

});

Step 5: Add Blade File

At last step we need to create imageUpload.blade.php file and in this file we will create form with file input button and written jquery ajax code. So copy bellow and put on that file.

resources/views/imageUpload.blade.php

<!DOCTYPE html>

<html>

<head>

<title>How to Upload Image using Ajax in Laravel 9? - Nicesnippets.com</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 using Ajax in Laravel 9? - Nicesnippets.com</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>

Run Laravel App:

All steps have been done, now you have to type the given command and hit enter to run the laravel app:

php artisan serve

Now, you have to open web browser, type the given URL and view the app output:

http://localhost:8000/image-upload

Output:

I hope it can help you...

#Laravel 9