Laravel Laravel 6

Laravel 7 Ajax Image Upload

Pinterest LinkedIn Tumblr

Step 1: Install Laravel 7 Project

I am going to install a laravel project using composer.

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

Step 2: Going inside of project using the command

cd laravel7

Step 3: Setup MySQL database

Now, configure this database in the .env file.

 DB_CONNECTION=mysql
 DB_HOST=127.0.0.1
 DB_PORT=3306
 DB_DATABASE=laravel7
 DB_USERNAME=root
 [email protected]

Step 4: Create employee_images Table and Model also.

Here, I have created migration for employee_images using Laravel 7 php artisan command, you can check command below.

php artisan make:migration create_employee_image_tabel

Once this command is done open file database/migrations and put code inside of migration file.

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

Now run migration command:

php artisan migrate

Step 5: Create a Model

After creating “employee_images” table you should create EmployeeImage model. So first we have to run bellow laravel artisan command for creating EmployeeImage model:

php artisan make:model EmployeeImage

Find a file inside of app folder

app/AjaxImage.php

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

Here I am going to create routes to get and post method. now open “routes/web.php” file and put below code.

routes/web.php

Route::get('employeeImageUpload', '[email protected]');
 
Route::post('employeeImageUpload', '[email protected]')->name('employeeImageUpload');

Step 6: Create Controller

Now I am going to create a new controller as EmployeeImageUploadController. you can find inside of app/Http/Controllers/EmployeeImageUploadController.php. in this controller we will mange layout and image validation with post request, run bellow command.

php artisan make:controller EmployeeImageUploadController

Now put code inside of the controller

app/Http/Controllers/EmployeeImageUploadController.php


<?php

namespace App\Http\Controllers;

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


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


    /**
     * Show the application employeeImageUploadPost.
     *
     * @return \Illuminate\Http\Response
     */
    
    public function employeeImageUploadPost(Request $request)
    {
      $validator = Validator::make($request->all(), [
        'nmae' => 'required',
        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
      ],
    //   Adding custom alert
      ['nmae.required' => 'A name is required']);
     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()]);
    
    }
}

Step 7: Create View

Here I am going to create employeeImageUpload.blade.php(resources/views/employeeImageUpload.blade.php) for layout and we will write design code here.

resources/views/employeeImageUpload.blade.php

<html>
<head>
	<title>Laravel 7 Ajax Image Upload with validation: Real Programmer</title>
	<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
	<script src="https://malsup.github.com/jquery.form.js"></script>
</head>
<body>


<div class="container">
  <h1>Laravel 7 Ajax Image Upload with validation: Real Programmer</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>Name</label>
      <input type="text" name="name" class="form-control" placeholder="Name">
    </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='name']").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 you can open bellow URL on your browser:

php artisan serve


Write A Comment