Ajax image Upload with preview in laravel 9 can be implement easily using the laravel file and storage providers.In a website Image uploading can be used in multiple places like set up a profile picture to providing the documents. Laravel 9 provides robust functionality to upload and process the image with security.
Laravel simply use Request file
method to access the uploaded file and then we can store or validate it with various methods provided by laravel. Even we can upload the image on different cloud servers like AWS.
Laravel has lots of features and packages available on the internet. So in this tutorial I will show you how laravel handle image uploading using it in-build methods.
In this tutorial we will use jQuery
JavaScript library to run the Ajax request to the server and upload the image as follow
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("form").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "url-to-upload",
type: 'POST',
data: formData,
success: function (data) {
//handle response },
cache: false,
contentType: false,
processData: false
});
});
</script>
Also Read : How to use Post Ajax Request in Laravel 8 / 9?
In this article I am going to create two routes, one controller, model, view and a js file to preview the image file.
Let’s start Ajax Image Upload with preview in Laravel 9 with example simple step by step
Step 1: Create a fresh laravel project
Open a terminal window and type below command to create a new project
composer create-project --prefer-dist laravel/laravel blog
You can also read this to start with new project
Step 2 : Create a table and model
Now, for an example i am creating here a table using migration and then i am going to fill the data in it, so create model and migration
php artisan make:model Article -m
this will generate the model and migration file
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasFactory;
}
and migration file database/migrations/timestamp_create_articles_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->string('email')->unique();;
$table->string('title');
$table->string('body')->nullable();
$table->string('image');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('articles');
}
}
and then migrate the migration
php artisan migrate
Step 3 : Create controller
Let’s create a controller and add a methods showArticle
and addArticle
php artisan make:controller ArticleController
and add the below code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Article;
use Illuminate\Support\Facades\Validator;
class ArticleController extends Controller
{
public function showForm(Request $request)
{
return view('articles.form');
}
function uploadArticle(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => "required",
'email' => "required|email",
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
$file = $request->file("image")->store("uploads/images");
// save image and name in database
$Article = new Article();
$Article->title = $request->title;
$Article->email = $request->email;
$Article->image = $file;
$Article->save();
return response()->json(["status" => true, "message" => "Image uploaded successfully"]);
}
}
In above code we used this code to store the image
$file = $request->file("image")->store("uploads/images");
// save image and name in database
$Article=new Article();
$Article->title=$request->title;
$Article->email=$request->email;
$Article->image= $file;
$Article->save();
Step 4: Create blade file for view
Now it’s time to show the form and validation message to our view, so let’s create the view file.
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ajax Image Upload with preview in Laravel 8/9 with example - Readerstacks </title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading">
<h2>Ajax Image Upload with preview in Laravel 8/9 with example - Readerstacks</h2>
</div>
<div class="panel-body">
<form method="post" id="uploadimageform" action="{{url('upload-article')}}" name="registerform">
<div class="form-group">
<label>Email</label>
<input type="text" name="email" value="" class="form-control" />
@csrf
</div>
<div class="form-group">
<label>Phone number</label>
<input type="text" name="phone_number" value="" class="form-control" />
</div>
<div class="form-group">
<label>Title</label>
<input type="text" name="title" value="" class="form-control" />
</div>
<div class="form-group">
<label>Image</label>
<input type="file" placeholder="Image" name="image" id="imgInp">
<img style="visibility:hidden" id="prview" src="" width=100 height=100 />
</div>
<div class="form-group">
<button class="btn btn-primary">Upload</button>
</div>
</form>
</div>
</div>
</div>
</body>
<script>
$(function() {
$("#uploadimageform").on("submit", function(e) {
e.preventDefault();
var action = $(this).attr("action");
var method = $(this).attr("method");
if (method == "post") {
var formData = new FormData(this);
$.ajax({
url: action,
type: 'POST',
data: formData,
success: function(data) {
alert("Form submitted successfully")
},
error: function(response, textStatus, errorThrown) {
console.log(response, textStatus, errorThrown)
$(".alert").remove();
var erroJson = JSON.parse(response.responseText);
for (var err in erroJson) {
for (var errstr of erroJson[err])
$("[name='" + err + "']").after("<div class='alert alert-danger'>" + errstr + "</div>");
}
},
cache: false,
contentType: false,
processData: false
});
}
return false;
});
});
</script>
</html>
Step 5: Add jQuery to handle the form submit
Here is the main logic to handle the form submit using jquery. In this step we will handle form submit using the query post method.
<script>
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#uploadimageform").on("submit", function(e) {
e.preventDefault();
var action = $(this).attr("action");
var method = $(this).attr("method");
if (method == "post") {
var formData = new FormData(this);
$.ajax({
url: action,
type: 'POST',
data: formData,
success: function(data) {
alert("Form submitted successfully")
},
error: function(response, textStatus, errorThrown) {
console.log(response, textStatus, errorThrown)
$(".alert").remove();
var erroJson = JSON.parse(response.responseText);
for (var err in erroJson) {
for (var errstr of erroJson[err])
$("[name='" + err + "']").after("<div class='alert alert-danger'>" + errstr + "</div>");
}
},
cache: false,
contentType: false,
processData: false
});
}
return false;
});
});
</script>
Here, we added ("#uploadimageform").on("submit", function() {}
to handle the submit event of form. Then, create a post request using $.ajax
and also get the value of form action
.
In next line we are handling the fail and success state. if the AJAX failed then it come into the fail block (Http response code 422). if the response code is 200 then it will come into success block.
$(".alert").remove();
var erroJson = JSON.parse(response.responseText);
for (var err in erroJson) {
for (var errstr of erroJson[err])
$("[name='" + err + "']").after("<div class='alert alert-danger'>" + errstr + "</div>");
}
Above code we are using to show the validation message below the each field.
Step 6 : Create Symblink for Storage
This is an important step and i suggest you to not skip this step, if you are going to show images in your website because you must need to access the image to show it on website so open config\filesystems.php and add public_path('uploads') => storage_path('app/uploads')
to links block
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => env('FILESYSTEM_DRIVER', 'public'),
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
],
],
'links' => [
public_path('storage') => storage_path('app/public'),
public_path('uploads') => storage_path('app/uploads'),
],
];
Since we are using in our controller this code
$destinationPath= '/uploads/images';
$storageDestinationPath=storage_path('app'.$destinationPath);
so we created a Symblink as
public_path('uploads') => storage_path('app/uploads'),
Now run artisan command to run Symblink
php artisan storage:link
Or for shared hosting
Route::get('/artisan-link', function () {
Artisan::call('storage:link');
});
NOTE: If you are using php artisan serve
and virtual host
to serve your application then above method will work perfectly but in case you are putting your public/index.php in root folder then you need to add public in URL. Example
URL for php artisan serve
and virtual host
will be and this will work perfectly
http://localhost:8000/uploads/images/16525039733751202249.png
and you are putting your public/index.php in root folder then you need to add public in URL
http://localhost/projectname/public/uploads/images/16525039733751202249.png
Step 7 : Create two routes in routes/web.php
One route for preview the html and another route for upload and compress the image.
routes/web.php
<?php
use App\Http\Controllers\ArticleController;
use Illuminate\Support\Facades\Route;
Route::get('/form',[ArticleController::class,"showForm"]);
Route::post('/upload-article',[ArticleController::class,"uploadArticle"]);
Results Screenshot:
I hope it will help you to implement Ajax form image uploading.