Laravel 8 Ajax Image Upload Example

May 21, 2021 . Admin

Hello Friends,

Now let's see example of how to use ajax image upload in laravel example. This is a short guide on laravel ajax image upload. Here you will learn how to ajax image upload. We will use how to ajax image upload in laravel. Let's get started with how to ajax image upload in laravel.

Here i will give you few step instruction to ajax image upload in laravel 8.

Step 1 : Install Laravel 8 Application
composer create-project --prefer-dist laravel/laravel blog
Step 2 : Database Configuration

Path: .env

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

In this step we have to first fire bellow command:

php artisan make:migration create_products_table

After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create categories table.

Path: database/migrations/create_products_table

<?php

	use Illuminate\Database\Migrations\Migration;
	use Illuminate\Database\Schema\Blueprint;
	use Illuminate\Support\Facades\Schema;

	class CreateProductsTable extends Migration
	{
	    /**
	     * Run the migrations.
	     *
	     * @return void
	     */
	    public function up()
	    {
	        Schema::create('products', function (Blueprint $table) {
	            $table->id();
	            $table->string('product_title');
	            $table->string('product_photo');
	            $table->timestamps();
	        });
	    }

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

?>

Now we require to run migration be bellow command:

php artisan migrate

Now we have to run bellow laravel artisan command for create Product model:

php artisan make:model Product

Path: app/Product.php

<?php

	namespace App;

	use Illuminate\Database\Eloquent\Model;

	/**
	    * Write code on Method
	    *
	    * @return response()
	*/

	class Product extends Model
	{
	  
	    protected $fillable = [
	        'product_title', 'product_photo'
	    ];
	}
?>
Step 4: Create Route

open your routes/web.php file and add following route.

Path: routes/web.php

<?php
  
	use Illuminate\Support\Facades\Route;
	  
	use App\Http\Controllers\ProductPhotoUploadController;
	  
	/*
	|--------------------------------------------------------------------------
	| 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('productPhotoUpload', [ProductPhotoUploadController::class, 'productPhotoUpload']);
	Route::post('productPhotoUpload', [ProductPhotoUploadController::class, 'productPhotoUploadPost'])->name('productPhotoUpload');
?>
Step 5: Create Controller

run bellow command for generate new controller:

php artisan make:controller ProductPhotoUploadController

Path: app/Http/Controllers/ProductPhotoUploadController.php

<?php

	namespace App\Http\Controllers;

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

	class ProductPhotoUploadController extends Controller
	{
	    /**
	     * Show the application productPhotoUpload.
	     *
	     * @return \Illuminate\Http\Response
	     */
	    public function productPhotoUpload()
	    {
	        return view('productPhotoUpload');
	    }

	    /**
	     * Show the application productPhotoUploadPost.
	     *
	     * @return \Illuminate\Http\Response
	     */
	    public function productPhotoUploadPost(Request $request)
	    {
	      $validator = Validator::make($request->all(), [
	        'product_title' => 'required',
	        'product_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
	      ]);


	      if ($validator->passes()) {

	        $input = $request->all();
	        if(!empty($input['image'])){    
	                $input['image'] = time().'-'.$request->image->getClientOriginalName();  
	                $request->image->move(public_path('images'), $input['image']);
	         }else{
	                unset($input['image']);
	         }

	        Product::create($input);

	        return response()->json(['success'=>'done']);
	      }

	      return response()->json(['error'=>$validator->errors()->all()]);
	    }
	}
?>
Step 6: Create View

Path: resources/views/ajaxImageUpload.blade.php

<!DOCTYPE html>
<html>
    <head>
        <title>Laravel 8 - Product Photo Uploading Tutorial</title>
        <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <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 mt-2">
          <div class="row">
            <div class="col-md-8 offset-md-2">
            <div class="card mt-2">
              <div class="card-header">
                <h2>Laravel 8 - Product Photo Uploading Tutorial</h2>
              </div>

              <div class="card-body">
                <form action="{{ route('productPhotoUpload') }}" 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>Product Title:</label>
                        <input type="text" name="product_title" class="form-control" placeholder="Add title">
                    </div>
                    <div class="form-group">
                      <label>Product Photo:</label>
                      <input type="file" name="product_photo" class="form-control">
                    </div>
                    <div class="form-group">
                      <button class="btn btn-success upload-image" type="submit">Upload Photo</button>
                    </div>

                  </form>
                </div>
              </div>
              </div>
            </div>
        </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='product_title']").val('');
                      alert('Photo 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>

Make sure you have to create "images" folder in your public directory.

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/productPhotoUpload

It will help you....

#Laravel 8 #Laravel