How to Upload Image in Laravel with Ajax

In this tutorial im going to describe how to upload image in larvel with Ajax example. Please follow mentioned below.

First let’s go to install laravel project

composer create-project --prefer-dist laravel/laravel ajaximage

lets go to .env folder and put database name and connect to database.

DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=ajax-imageDB_USERNAME=rootDB_PASSWORD=

Nex to Create ajax_images Table and Model

php artisan make:migration create_ajax_image_tabel

Next go to ajaximage table and paste below code.

<?phpuse Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;class CreateAjaxImageTabel extends Migration{    /**     * Run the migrations.     *     * @return void     */    public function up()    {        Schema::create('ajax_image_tabel', function (Blueprint $table) {            $table->id();            $table->string('title');            $table->string('image');            $table->timestamps();        });    }    /**     * Reverse the migrations.     *     * @return void     */    public function down()    {        Schema::dropIfExists('ajax_image_tabel');    }}

Now we require to run migration be bellow command:

php artisan migrate

Now table has been successfully migrated to database.

Next to create model run below code

php artisan make:model AjaxImage

Go to your model file and paste below code.

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class AjaxImage extends Model{    /**     * The attributes that are mass assignable.     *     * @var array     */    protected $fillable = [        'title', 'image'    ];}

Step 4: Create Route

In this is step we need to create route for ajax image upload layout file and another one for post request. so open your routes/web.php file and add following route.

routes/web.php

Route::get('ajaxImageUpload', 'AjaxImageUploadController@ajaxImageUpload');Route::post('ajaxImageUpload', 'AjaxImageUploadController@ajaxImageUploadPost')->name('ajaxImageUpload');

Step 5: Create Controller

php artisan make:controller AjaxImageUploadController

Next go to AjaxImageUploadController and paste below code.

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use Validator;use App\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()]);    }}

Next to create view

resources/views/ajaxImageUpload.blade.php

<!DOCTYPE html><html><head>	<title>LaravelAmit - 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  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>

Now go to your terminal and paste below code.

php artisan serve

Now go to phpmyadmin and check table data has been store successfully.

Thanks.

Related Posts

Blade in Laravel

Blade is the simple,yet powerful templating engine that is included with laravel. Blade does not restrict you from using plain php code in your templates. Blade templates…

Read More

CRUD USING QUIRY BUILDER IN LARAVEL.

We are performing crud opertion using quiry builder in laravel STEP : 1 Create Laravel project by running this command in terminal CMND :– Laravel new project_name…

Read More

Controller In Laravel

Controllers can group related request handling logic into a single class, Instead of defining all of your request handling logic as closure in route files ,you may…

Read More

LARAVEL ROUTING

All Laravel routes are define in route files , which are located in the route directory ,These file are automatically loaded by the framework. The most basic…

Read More

MVC (MODEL VIEW CONTROLLER)

MVC stands for Model–view–controller. The MVC is an architectural pattern model that seprates an applications into three logical components.(Model , View, Controller) MVC was first introduce in…

Read More

ReflectionException : Class BlogsTableSeeder does not exist

When i type php artisan db:seed command. It’s showing this type of errors. [ReflectionException]Class UserTableSeeder does not exist Here is my BlogsTableSeeder <?phpuse Illuminate\Database\Seeder;class BlogsTableSeeder extends Seeder{…

Read More
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x