Laravel Ajax Image Upload with Example

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Today now in this example, i will explain you how to we can jquery ajax image upload in laravel application .Here i will show you laravel image upload by using ajax. So here we can easily upload image by using ajax in laravel 8 application. Here i will tell you how to jquery ajax image upload in laravel application. Here i will show a full example of larvael ajax image upload.

From here you will learn how to upload image by using jquery ajax. Now in this example i use FormJS for fire Ajax on that way we can simply use in laravel validation and also print laravel error message.

Now here i  will give you a full example of ajax image uploading step by step like create laravel project, migration, model, route, blade file etc. So you just need to  follow few steps.

Step 1 : Install Laravel Application

Here we are going this project from scratch, So we need to get a fresh Laravel application by using bellow command. So open your terminal OR command prompt and then run bellow command:

composer create-project --prefer-dist laravel/laravel blog
Step 2: Database Configuration

Now in this step, we need to make database configuration, we need to add following details on your .env file.

1.Database Username

1.Database Password

1.Database Name

So in .env file also available host and port details, we can aslo configure all details as in our system, So you can put like as bellow:

following path: .env

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Step 3: Create ajax_images Table and Model

So now in this step we have to create a migration for images table by using Laravel php artisan command, so need to fire bellow command:

php artisan make:model Image -m

Then after this command we have to put bellow code in your migration file for create Image table.

following path:/database/migrations/2020_01_10_102325_create_images_table.php

<?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->bigIncrements('id');
            $table->string('title');
            $table->string('image');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('images');
    }
}

Now here we require to run migration be bellow command:

php artisan migrate

After that you have to put bellow code in your model file for create Image table.

following path:/app/Image.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
    protected $fillable = ['title','image'];
}
Step 4: Create Route

Now in this is step we need to create route for our ajax image upload layout file and another one for post request. So open following fille path

following path:/routes/web.php

Route::get('imageUploadAjax', 'ImageUploadAjaxController@imageUploadAjax');
Route::post('imageUploadAjax', 'ImageUploadAjaxController@imageUploadAjaxPost')->name('imageUploadsAjax');
Step 5: Create Controller

So now in this step now we should create new controller as ImageUploadAjaxController, So then run bellow command for generate new controller

php artisan make:controller ImageUploadAjaxController

Now in this step, this controller will manage layout and image validation with post request,bellow content in controller file.following fille path

following path:/app/Http/Controllers/ImageUploadAjaxController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use App\Model\Image;

class ImageUploadAjaxController extends Controller
{
  /**
     * Show the application ajaxImageUpload.
     *
     * @return \Illuminate\Http\Response
     */
    public function imageUploadAjax()
    {
      return view('imageUploadAjax');
    }
    /**
     * Show the application ajaxImageUploadPost.
     *
     * @return \Illuminate\Http\Response
     */
    public function imageUploadAjaxPost(Request $request)
    {
      $validator = Validator::make($request->all(), [
        'title' => 'required',
        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
      ]);

      if ($validator->passes()) {

        $inputData['title'] = $request->title;
        $inputData['image'] = time().'.'.$request->image->extension();
        $request->image->move(public_path('images'), $inputData['image']);

        Image::create($inputData);
        
        return response()->json(['success'=>'done']);
      }
      return response()->json(['error'=>$validator->errors()->all()]);
    }
}
Step 6: Create View

Now in Last step, let’s create ajaxImageUpload.blade.php(resources/views/imageUploadAjax.blade.php) For layout and we will write design code here and also form for ajax image upload, So put following code:

following path:resources/views/imageUploadAjax.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 6 - Ajax Image Uploading Tutorial - CodingsPoint.com</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>
</head>
<body>
<div class="container">
  <div class="col-md-8 col-md-offset-2">
    <h3>Laravel 6 - Ajax Image Uploading Tutorial-CodingsPoint.com</h3>
    <form action="{{ route('imageUploadsAjax') }}" 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>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>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/formjs/1.1.1/formjs.min.css"></script>
<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>

Create folder images

Now need to create “images” folder in your public directory.

following path:/public/images

Now we are ready to run our example so run bellow command so quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/imageUploadAjax

Read Also : Laravel 8 Eloquent Global Scope Tutorial Example

I hope it will help you. Also you can follow us on Facebook

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →