Ajax Image Upload Example with Validation in PHP Laravel Framework
In this post, I am going to explain “How to upload image using ajax in laravel “. Laravel provide very simple way to store image or file on server. Laravel also provide validation for max file size, Image mime type and height width etc.
So, If we make image upload using jquery ajax then it become good for our GUI and best. So Today in this post we will learn how to upload image using jquery ajax.
Here i give you full example of ajax image uploading step by step like create laravel project, migration, model, route, blade file etc. So you have to just follow few step as listed bellow.
Step 1:- Install laravel using below command
1 2 3 | composer create-project --prefer-dist laravel/laravel ajaxImageDemo |
Step 2:- After installation need to setup database configuration in .env file like
1 2 3 4 5 6 | DB_HOST=localhost DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret |
Step 3:- Now create image table, Model and Migration for store image in database
1 2 3 | php artisan make:migration create_image_tabel |
After this command you will find image migration file on following path database/migrations and you have to put bellow code in your migration file for create table.
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 | <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateImageTabel extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('ajax_images', function (Blueprint $table) { $table->increments('id'); $table->string('image'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop("images"); } } |
Now we need to run migration command
1 2 3 | php artisan migrate |
After create table, Now we need to create Model using below command
1 2 3 | php artisan make:model Image |
Now copy below code and paste in Image model file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?php namespace App; use Illuminate\Database\Eloquent\Model; class Image extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'image' ]; } |
Step 4:- In this step we need to create route for ajax image upload in route file
routes/web.php
1 2 3 4 | Route::get('ajax-upload-image','DemoController@index'); Route::post('uploadImage','DemoController@uploadImage'); |
Step 5:- Now we should create controller as DemoController.php file
app/Http/Controllers/DemoController.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 | <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Validator; use App\Image; class DemoController extends Controller { /** * Show the application . * * @return \Illuminate\Http\Response */ public function index() { return view('ajaxImageUpload'); } /** * Show the application . * * @return \Illuminate\Http\Response */ public function uploadImage(Request $request) { $validator = Validator::make($request->all(), [ 'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); if ($validator->passes()) { $input = $request->all(); $input['image'] = time().'.'.$request->image->getClientOriginalExtension(); $request->image->move(public_path('images'), $input['image']); Image::create($input); return response()->json(['success'=>'done']); } return response()->json(['error'=>$validator->errors()->all()]); } } |
Step 6:- Now we should create view file ajaxImageUpload.blade.php for layout, So just copy below code paste in view file.
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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Webprepration Demo</title> <link rel="icon" href="http://webprepration.com/wp-content/uploads/2017/11/wp-65x65.png" sizes="32x32" /> <link rel="icon" href="http://webprepration.com/wp-content/uploads/2017/11/wp-300x300.png" sizes="192x192" /> <link rel="apple-touch-icon-precomposed" href="http://webprepration.com/wp-content/uploads/2017/11/wp-300x300.png" /> <meta name="msapplication-TileImage" content="http://webprepration.com/wp-content/uploads/2017/11/wp-300x300.png" /> <!-- Bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" type="text/css" href="http://webprepration.com/demo/css/style.css"> <link href="public/css/sweetalert.css" rel="stylesheet"> </head> <body> <nav class="navbar navbar-default navbar-static-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">WEB PREPRATION</span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="http://webprepration.com/">WEB PREPRATION</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li class="sa"><a href="http://webprepration.com/category/php/">PHP</a></li> <li class="sa"><a href="http://webprepration.com/category/wordpress/">WordPress</a></li> <li class="sa"><a href="http://webprepration.com/category/wordpress/">Plugins</a></li> <li class="sa"><a href="http://webprepration.com/category/codeignitor/">CodeIgnitor</a></li> <li class="sa"><a href="http://webprepration.com/category/laravel/">Laravel</a></li> </ul> </div><!--/.nav-collapse --> </div> </nav><!--/nav--> <div class="container"> <div class="panel panel-primary"> <div class="panel-heading">Upload Image Using Ajax in Laravel </div> <div class="panel-body"> <div class="panel-body"> <div class="row"> <form action="" method="post" id="sitelogo"> <div class="form-group"> <input type="file" class="form-control" id="logo" name="logo"> </div> <div class="form-group"> <img id="myImg" src="{{url('/')}}/public/uploads/{{ (isset($setting->logo) && $setting->logo) !='' ? $setting->logo : 'images.jpg'}}" style="max-width: 500px;max-height: 400px;width: 100%;"> </div> </form> </div> </div> </div> </div> </div> <div class="footer-bottom"> <div class="container"> <div class="row"> <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4"> <div class="copyright" style="font-family: sans-serif;"> Web Prepration <span style="color: #504f4f;">Copyright © 2017.</span> </div> </div> <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4"> <div class="copyright" align="center"> <a href="http://webprepration.com" style="color: #337ab7;">Home</a>| <a href="http://webprepration.com/about-us/" style="color: #337ab7;">About Us</a>| <a href="http://webprepration.com/contact-us/" style="color: #337ab7;">Contact</a> </div> </div> <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4"> <div class="design"> <a href="http://webprepration.com" style="color: #0274be;">Back to Top</a> </div> </div> </div> </div> </div> <script src="{{asset('public/js/ajaxscript.js')}}"></script> <script src="{{asset('public/js/sweetalert.min.js')}}"></script> <script type="text/javascript"> $("#logo").change(function () { jQuery.ajax({ url:"{{url('/')}}/uploadImage", headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" }, data:new FormData($("#sitelogo")[0]), method:"POST", processData: false, contentType: false, success:function(data){ console.log(data); }, error:function(error){ console.log(error); } }); }; </script> </body> </html> |
Now we are ready to run example, So just run below command
1 2 3 | php artisan serve |
Now you can open below command on browser
1 2 3 | http://localhost:8000 |
I hope you might have understood it properly, keep reading our other blogs posts for more coding tricks.
Thanks!!
Hey there just wanted to give you a quick heads up. The
words in your post seem to be running off the screen in Ie.
I’m not sure if this is a formatting issue or something to do with internet
browser compatibility but I thought I’d post to let you know.
The style and design look great though! Hope you get the issue solved soon. Thanks
Hi there! Do you use Twitter? I’d like to follow you
if that would be okay. I’m definitely enjoying your
blog and look forward to new updates.
Attractive section of content. I just stumbled upon your blog and
in accession capital to assert that I get actually enjoyed account your blog posts.
Any way I will be subscribing to your feeds and even I achievement you access
consistently fast.
Thanks for a marvelous posting! I seriously enjoyed reading it, you can be a great
author. I will remember to bookmark your blog and will come
back in the future. I want to encourage yourself to
continue your great work, have a nice holiday weekend!
Hello there! I could have sworn I’ve been to this website before but after reading through
some of the post I realized it’s new to me. Anyhow, I’m definitely happy
I found it and I’ll be bookmarking and checking back often!
Wonderful article! That is the kind of information that are supposed to be shared across the net.
Shame on Google for no longer positioning this post upper!
Come on over and discuss with my website .
Thank you =)
Wonderful article! This is the kind of information that
should be shared across the net. Disgrace on Google for
no longer positioning this publish higher! Come on over and visit my
website . Thank you =)