Laravel 6 Ajax Image Upload example tutorial
In this tutorial, we will explain to you how to upload images with ajax in Laravel Framework (Laravel 6 Ajax Image Upload example tutorial).
In this example, we will upload the images with the validation in the folder. so you can follow the below step for image upload using ajax in laravel 6.
Overview
Step 1: Install Laravel
Step 2: Setting Database Configuration
Step 3: Create Table using migration
Step 4: Create Route
Step 5: Create a Model and Controller
Step 6: Create Blade Files
Step 7: Run The Application
Step 1: Install Laravel
We are going to install laravel 6, so first open the command prompt or terminal and go to go to xampp htdocs folder directory using the command prompt. after then run the below command.
1 | composer create-project --prefer-dist laravel/laravel larave6_ajax_image |
Step 2: Setting Database Configuration
After the complete installation of laravel. we have to database configuration. now we will open the .env file and change the database name, username, password in the .env file. See below changes in a .env file.
1 2 3 4 5 6 | DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=Enter_Your_Database_Name(larave6_ajax_image) DB_USERNAME=Enter_Your_Database_Username(root) DB_PASSWORD=Enter_Your_Database_Password(root) |
Step 3: Create Table using migration
Now, We need to create a migration. so we will below command using create the images table migration.
1 | php artisan make:migration create_images_table --create=images |
After complete migration. we need below changes in the database/migrations/create_images_table file.
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 | <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateImagesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('images', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('image'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('images'); } } ?> |
Run the below command. after the changes above file.
1 | php artisan migrate |
Step 4: Create Route
Add the following route code in the “routes/web.php” file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php /* |-------------------------------------------------------------------------- | 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('image', 'ImageController@index'); Route::post('image', 'ImageController@save'); ?> |
Step 5: Create a Model and Controller
Here below command help to create the controller and model.
1 | php artisan make:controller ImageController --resource --model=Image |
Image.php
1 2 3 4 5 6 7 8 9 10 | <?php namespace App; use Illuminate\Database\Eloquent\Model; class Image extends Model { protected $fillable = [ 'image' ]; } ?> |
ImageController.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 | <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Validator,Redirect,Response,File; use App\Image; class ImageController extends Controller { /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('image'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function save(Request $request) { $this->validate($request, [ 'image' => 'required', 'image.*' => 'mimes:jpeg,jpg,gif,png' ]); if($request->file('images')){ $file=$request->file('images'); $name=$file->getClientOriginalName(); $file->move('image',$name); Image::insert( ['image'=> $name]); return Response()->json([ "success" => true, "image" => $name ]); }else{ return Response()->json([ "success" => false ]); } } } ?> |
Step 6: Create Blade Files
So finally, first we will create the image.blade.php files in “resources/ views/student/” directory.
image.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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | <!DOCTYPE html> <html lang="en"> <head> <title>Laravel 6 Ajax Image Upload Example Tutorial - XpertPhp</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <script> $(document).ready(function (e) { $('#preview_img').hide(); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $('#image').change(function(){ let reader = new FileReader(); reader.onload = (e) => { $('#preview_img').show(); $('#preview_img').attr('src', e.target.result); } reader.readAsDataURL(this.files[0]); }); $('#form').submit(function(e) { e.preventDefault(); var formData = new FormData(this); $.ajax({ type:'POST', url: "{{ url('image')}}", data: formData, cache:false, contentType: false, processData: false, success: (data) => { if(data.success == true){ this.reset(); alert('Image has been uploaded successfully'); } }, error: function(data){ console.log(data); } }); }); }); </script> </head> <body> <div class="container"> <form id="form" enctype="multipart/form-data" method="post"> <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>"> <div class="form-group"> <label for="image">Choose Image:</label> <input required type="file" class="form-control" id="image" name="image"> </div> <div class="row"> <div class="col-md-12"> <img id="preview_img" src="" alt="preview image" width="100"> </div> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div> </body> </html> |
Step 7: Run The Application
We can start the server and run this application using the below command.
1 | php artisan serve |
Now we will run our example using the below Url in the browser.
1 | http://127.0.0.1:8000/image |
Recommended Posts
Laravel 6 ajax form submit with Jquery validation example
Laravel 6 Pagination Example Tutorial
Laravel 6 pdf generator tutorial using dompdf