In this tutorial you will learn about the Laravel 8 Ajax Image Upload Example and its application with practical example.
In this Laravel 8 Ajax Image Upload Example tutorial I will show you how to upload image using ajax in laravel application. In this tutorial you will learn to upload image file using ajax in laravel 8. You will also learn to upload and save image in laravel 8 using ajax. In this laravel ajax image upload example, I’ll show you how to validate upload image into folder and then save it into database using ajax. Before saving image into database we will validate image and then save it into directory using. Before uploading the image we will perform server side validation. After successfully image upload into the database and folder we will display uploaded image on the screen.
Laravel 8 Ajax Image Upload Example
In this step by step tutorial I will demonstrate you with an example to upload image using ajax in laravel application. Please follow the instruction given below:
Step 1 : Install Laravel 8 Application
First of all we need to create a fresh laravel project, download and install Laravel 8 using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
Step 2 : Database Configuration
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 |
DB_HOST=localhost DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret |
Step 3: Create ajax_images Table and Model
Now, we have to define table schema for ajax_image table. Open terminal and let’s run the following command to generate a migration along with model file to create ajax_image table in our database.
1 |
php artisan make:migration create_ajax_image_tabel |
Once this command is executed you will find a migration file created under “database/migrations”. lets open migration file and put following code in it –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAjaxImageTabel extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('ajax_images', function (Blueprint $table) { $table->id(); $table->string('title'); $table->string('image'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop("ajax_images"); } } |
Now, run following command to migrate database schema.
1 |
php artisan migrate |
After creating “ajax_images” table ,create AjaxImage model for Categories.
1 |
php artisan make:model AjaxImage |
Now, in this step we will create model file app/Models/AjaxImage.php and put the following code in item.php file:
app/Models/AjaxImage.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class AjaxImage extends Model { use HasFactory; protected $fillable = [ 'title', 'image' ]; } |
Step 4: Create Route
Now, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\AjaxImageUploadController; /* |-------------------------------------------------------------------------- | 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('ajaxImageUpload', [AjaxImageUploadController::class, 'ajaxImageUpload']); Route::post('ajaxImageUpload', [AjaxImageUploadController::class, 'ajaxImageUploadPost'])->name('ajaxImageUpload'); |
Step 5: Create Controller
Now create new controller as AjaxImageUploadController in this path app/Http/Controllers/AjaxImageUploadController.php.
1 |
php artisan make:controller AjaxImageUploadController |
app/Http/Controllers/AjaxImageUploadController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Validator; use App\Models\AjaxImage; class AjaxImageUploadController extends Controller { /** * Show the application ajaxImageUpload. * * @return \Illuminate\Http\Response */ public function ajaxImageUpload() { return view('ajaxImageUpload'); } /** * Show the application ajaxImageUploadPost. * * @return \Illuminate\Http\Response */ public function ajaxImageUploadPost(Request $request) { $validator = Validator::make($request->all(), [ 'title' => 'required', 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); if ($validator->passes()) { $input = $request->all(); $input['image'] = time().'.'.$request->image->extension(); $request->image->move(public_path('images'), $input['image']); AjaxImage::create($input); return response()->json(['success'=>'done']); } return response()->json(['error'=>$validator->errors()->all()]); } } |
Step 6: Create View
Now create ajaxImageUpload.blade.php(resources/views/ajaxImageUpload.blade.php) for layout design code and form for ajax image upload.
resources/views/ajaxImageUpload.blade.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
<!DOCTYPE html> <html> <head> <title>Laravel 8 - Ajax Image Uploading Tutorial</title> <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src="http://malsup.github.com/jquery.form.js"></script> </head> <body> <div class="container"> <h1>Laravel 8 - Ajax Image Uploading Tutorial</h1> <form action="{{ route('ajaxImageUpload') }}" enctype="multipart/form-data" method="POST"> <div class="alert alert-danger print-error-msg" style="display:none"> <ul></ul> </div> <input type="hidden" name="_token" value="{{ csrf_token() }}"> <div class="form-group"> <label>Alt Title:</label> <input type="text" name="title" class="form-control" placeholder="Add Title"> </div> <div class="form-group"> <label>Image:</label> <input type="file" name="image" class="form-control"> </div> <div class="form-group"> <button class="btn btn-success upload-image" type="submit">Upload Image</button> </div> </form> </div> <script type="text/javascript"> $("body").on("click",".upload-image",function(e){ $(this).parents("form").ajaxForm(options); }); var options = { complete: function(response) { if($.isEmptyObject(response.responseJSON.error)){ $("input[name='title']").val(''); alert('Image Upload Successfully.'); }else{ printErrorMsg(response.responseJSON.error); } } }; function printErrorMsg (msg) { $(".print-error-msg").find("ul").html(''); $(".print-error-msg").css('display','block'); $.each( msg, function( key, value ) { $(".print-error-msg").find("ul").append('<li>'+value+'</li>'); }); } </script> </body> </html> |
Note:- Do remember to create “images” folder in public directory.
Run Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Now, open the following URL in browser to see the output –
1 |
http://localhost:8000/ajaxImageUpload |