In this post, we’ll show you how to upload an image using ajax in Laravel 8 from the ground up. More often than not, we need to save image data with an ajax request in a Laravel application without refreshing the page or reloading it. Laravel 8 Image Upload Using Ajax Example If you know how to use the form submit via ajax in Laravel, then uploading pictures with ajax and saving them in the database is also simple. Using the store method on an uploaded file instance, Laravel makes it simple to keep stored files. Call the store method with the path where you want to store your file.
Download the latest version of Laravel and create a new project using composer
Step 1 : Install Laravel 8 App just run the below command
Composer create-project laravel/laravel imageupload
Step 2: Create Database Now open your .env file and add the database name, user name, and password to it.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=imageupload_db
DB_USERNAME=root
DB_PASSWORD=

Step 3: Make a Model & Migrations File Now run the command to generate the model and migration file.
php artisan make:model Image -m

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateImagesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable();
$table->string('path')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('images');
}
}
Now you may proceed by adding the code to your migration file and executing the migrate command, which will create a new table in your database.
php artisan migrate
If we want to save data in a database, we must alter the fillable property of the model, which columns should be updated when the information is saved.
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', 'path'];
}
Step 4: Create Routes In this stage, you’ll need to add two routes to your web.php file, as shown below.
routes\web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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::get('/', function () {
return view('images');
});
Route::get('upload-images', [ ImageController::class, 'index' ]);
Route::post('upload-images', [ ImageController::class, 'storeImage' ])->name('images.store');
Step 5: Create a Image Upload Controller
php artisan make:controller ImageController
After executing the above command, you should have a new controller file in your current directory with the following code on it.
app/Http/Controllers/ImageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ImageControlle extends Controller
{
public function index()
{
return view('images');
}
public function storeImage(Request $request)
{
$request->validate([
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = new Image;
if ($request->file('file')) {
$imagePath = $request->file('file');
$imageName = $imagePath->getClientOriginalName();
$path = $request->file('file')->storeAs('uploads', $imageName, 'public');
}
$image->name = $imageName;
$image->path = '/storage/'.$path;
$image->save();
return response()->json('Image uploaded successfully');
}
}
Step 6: Create Blade File
Now create a images file in view section and put the below code on it.
resources\views\images.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel Image Upload Using Ajax Example with Coding Driver</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<h2 class="p-2">Laravel Image Upload Using Ajax Example with- <a href="http://mycodeshub.com/">mycodeshub.com</a></h2>
<div class="col-6">
<div class="container mt-4">
<form method="post" id="upload-image-form" enctype="multipart/form-data">
@csrf
<div class="form-group">
<input type="file" name="file" class="form-control" id="image-input">
<span class="text-danger" id="image-input-error"></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Upload</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#upload-image-form').submit(function(e) {
e.preventDefault();
let formData = new FormData(this);
$('#image-input-error').text('');
$.ajax({
type:'POST',
url: `/upload-images`,
data: formData,
contentType: false,
processData: false,
success: (response) => {
if (response) {
this.reset();
alert('Image has been uploaded successfully');
}
},
error: function(response){
console.log(response);
$('#image-input-error').text(response.responseJSON.errors.file);
}
});
});
</script>
</body>
</html>
When you install laravel, it creates a new directory inside your webroot called ‘storage’ (in most cases). This is where all of your application files will be stored.
php artisan storage:link
Developers, today we’re going to learn the LaraLaravel 8 Ajax Image Upload with Validation Tutorial Example. I hope this tutorial works well for you; if you have any questions, please leave a comment below. Today’s Laravel Image Uploader Example Tutorial From Scratch has come to an end. If you want more information about Laravel, please visit our blog on a daily basis. Thank you very much!
FAQ
how to update image in laravel using ajax
Laravel is an open-source PHP web framework, meaning it’s a software with codes that are free to use. It was created by Taylor Otwell and has been downloaded over 100 million times as of June 2017. Laravel provides tools for developing web applications such as validation, localization, scaffolding and more. This article will show you how to update image in laravel using ajax. You can find out more about this topic here:
http://mycodeshub.com/laravel-8-image-upload-using-ajax-example/
Leave a Reply
You must be logged in to post a comment.