Laravel Ajax Image Upload Tutorial With Example

Hello developers, In this example, I will demonstrate to you how to do Laravel Ajax Image Upload Tutorial With Example. We will use the jQuery form plugin to walk through going from a brand new Laravel 5.6 application to send ajax request. This Plugin allows you to quickly and unobtrusively upgrade forms to use AJAX. The server checks all field against defined validation, and if any of the validation breaks, it will show error messages.

Laravel Ajax Image Upload Tutorial With Example

We are going to Configure Laravel Project.

#1: Download Laravel Project

Establish  Laravel Project by the typing following command.

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

#2: Configure SQL Database

Now we can setup database credentials.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ajaximageupload
DB_USERNAME=root
DB_PASSWORD=

#3: Build Model and Migration File

php artisan make:model Imageupload -m

It will create an Imageupload.php file and also create a create_imageuploads_table.php  migration file.

//create_imageuploads_table

public function up()
    {
        Schema::create('imageuploads', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('price');
            $table->string('image');
            $table->timestamps();
        });
    }

Put following code in Imageupload.php file. We will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment by default.

//Imageupload.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Imageupload extends Model
{
    protected $fillable = [
        'name','price', 'image'
    ];
}

#4: Create a View File.

Create a file in resources/views/imageupload.blade.php and put this following code in it.

<!-- imageupload.blade.php -->

<!DOCTYPE html>
<html>
<head>
<title>Laravel Ajax Image Upload Tutorial With Example</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
	  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
</head>
<body>
<div class="container">
  <h1>Laravel Ajax Image Upload Tutorial With Example</h1>
    <form action="{{ url('/imageupload/store') }}" enctype="multipart/form-data" method="post">
    @csrf
    <div class="form-group row">
      <label for="name" class="col-md-4 col-form-label text-md-right">Product Name:</label>
        <div class="col-md-2">
          <input id="name" type="text" class="form-control" name="name">
        </div>
    </div>
    <div class="form-group row">
      <label for="price" class="col-md-4 col-form-label text-md-right">Product Price:</label>
        <div class="col-md-2">
          <input id="price" type="text" class="form-control" name="price">
        </div>
    </div>
    <div class=" form-group row">
        <div class="col-md-4"></div>
        <div class="col-md-2">
          <input type="file" name="image" class="form-control"> 
        </div>
    </div>
    <div class=" form-group row">
        <div class="col-md-4"></div>
        <div class="col-md-2">
            <button type="submit" id="submit" class="btn btn-success">Upload</button>
        </div>
    </div>
  </form>
</div>
</body>
</html>

#5: Create one controller

$ php artisan make:controller ImageuploadController

It will build a controller file called ImageuploadController.php.

//ImageuploadController.php

public function create()
    {
        return view('imageupload');
    }

#6: Define Route

We register all route in a web.php file.

//web.php

Route::get('/imageupload','ImageuploadController@create');
Route::post('/imageupload/store','ImageuploadController@store');

How to Upload Ajax Image in Laravel

#7: Add jQuery Code

Now, Include the jQuery.ajaxForm() function that submits the request to the server with all input field. This method supports numerous options which allow you to have full control over how the data is submitted. Submitting a form with AJAX doesn’t get any easier than this.

<!-- imageupload.blade.php -->

<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
  jQuery("body").on("click","#submit",function(e)
  {
    jQuery(this).parents("form").ajaxForm
    ({
        complete: function(response) 
        {
    	      if($.isEmptyObject(response.responseJSON.error))
            {
                jQuery('.alert-danger').hide(); 
    		        jQuery("input[name='name']").val('');
                jQuery("input[name='price']").val('');
        
    		        alert('Image has been successfully uploaded');
        
    	      }
            else
            {
                jQuery('.alert-danger').html('');
    		        jQuery.each(response.responseJSON.error, function(key, value)
                {
                  jQuery('.alert-danger').show();
                  jQuery('.alert-danger').append('<p>'+value+'</p>');
                });
    	    }
        }
    });
  });
</script>

Add jQuery code into the imageupload.blade.php file.

<!-- imageupload.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title>Laravel Ajax Image Upload Tutorial With Example</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
	  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
</head>
<body>
<div class="container">
  <h1>Laravel Ajax Image Upload Tutorial With Example</h1>
    <form action="{{ url('/imageupload/store') }}" enctype="multipart/form-data" method="POST">
    <div class="alert alert-danger" style="display:none"></div>
    @csrf
    <div class="form-group row">
      <label for="name" class="col-md-4 col-form-label text-md-right">Product Name:</label>
        <div class="col-md-2">
          <input id="name" type="text" class="form-control" name="name">
        </div>
    </div>
    <div class="form-group row">
      <label for="price" class="col-md-4 col-form-label text-md-right">Product Price:</label>
        <div class="col-md-2">
          <input id="price" type="text" class="form-control" name="price">
        </div>
    </div>
    <div class=" form-group row">
        <div class="col-md-4"></div>
        <div class="col-md-2">
          <input type="file" name="image" class="form-control"> 
        </div>
    </div>
    <div class=" form-group row">
        <div class="col-md-4"></div>
        <div class="col-md-2">
            <button type="submit" id="submit" class="btn btn-success">Upload</button>
        </div>
    </div>
  </form>
</div>

<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
  jQuery("body").on("click","#submit",function(e)
  {
    jQuery(this).parents("form").ajaxForm
    ({
        complete: function(response) 
        {
    	      if($.isEmptyObject(response.responseJSON.error))
            {
                jQuery('.alert-danger').hide(); 
    		        jQuery("input[name='name']").val('');
                jQuery("input[name='price']").val('');
        
    		        alert('Image has been successfully uploaded');
        
    	      }
            else
            {
                jQuery('.alert-danger').html('');
    		        jQuery.each(response.responseJSON.error, function(key, value)
                {
                  jQuery('.alert-danger').show();
                  jQuery('.alert-danger').append('<p>'+value+'</p>');
                });
    	    }
        }
    });
  });
</script>
</body>
</html>

If you submitted the form and there is no error, then you can see an alert message in your window screen.

#8: Store data to the database

Next, we are set to fill in store () method with the logic to store data to the database. First, we define the validation for a form field. If any fields fail to validate then it through an error. If validation passes then data store to the database successfully. Put the following code in ImageuploadController under store() method.

//ImageuploadController.php

use Validator;
use App\Imageupload;

public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'price' => 'required',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
          ]);
    
          if ($validator->passes())
          {
            $data = $request->all();
            $data['image'] = time().'.'.$request->image->getClientOriginalExtension();
            $request->image->move(public_path('images'), $data['image']);
            Imageupload::create($data);
            return response()->json(['success'=>'Data is successfully added']);
          }
          return response()->json(['error'=>$validator->errors()->all()]);
    }

 

laravel ajax image upload example

Also, you can see the images in public/images folder in your application.

Final Code of ImageuploadController looks like that.

//ImageuploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use App\Imageupload;

class ImageuploadController extends Controller
{
    public function create()
    {
        return view('imageupload');
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'price' => 'required',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
          ]);
    
          if ($validator->passes())
          {
            $data = $request->all();
            $data['image'] = time().'.'.$request->image->getClientOriginalExtension();
            $request->image->move(public_path('images'), $data['image']);
            Imageupload::create($data);
            return response()->json(['success'=>'Data is successfully added']);
          }
          return response()->json(['error'=>$validator->errors()->all()]);
    }
}

You can see the database in below screenshot.

 

Ajax Image Upload with Validation in laravel

At last, our Laravel Ajax Image Upload Tutorial With Example is over.

Post Your Thoughts

This site uses Akismet to reduce spam. Learn how your comment data is processed.