laravel 9

Laravel 9 Ajax Image Upload

Pinterest LinkedIn Tumblr

Step 1: Install Laravel 9 Project

I am going to install a laravel project using composer.

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

Step 2: Going inside of project using the command

cd laravel9

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=laravel9
 DB_USERNAME=root
 DB_PASSWORD=root@123

Step 4: Create ajax_images Table and Model also.

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

php artisan make:migration create_ajaxImages_table

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

<?php

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

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

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

Now run migration command:

php artisan migrate

Step 5: Create a Model

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

php artisan make:model AjaxImage

Find a file inside of app folder

app/Models/AjaxImage.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class AjaxImage extends Model
{
     protected $fillable = [
         'name', 'image'
     ];

    use HasFactory;
}

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

<?php 

use App\Http\Controllers\EmployeeImageUploadController;

Route::get('employeeImageUpload', [EmployeeImageUploadController::class,'employeeImageUpload']);
 

Route::get('employeeImageUpload', [EmployeeImageUploadController::class,'employeeImageUploadPost'])->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\Models\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(), [
        'name' => 'required',
        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
      ]);
     if ($validator->passes()) {
        $input['image'] = time().'.'.$request->image->extension();
        $request->image->move(public_path('images'), $input['image']);
        $data = ['name' => $request->name,'image'=>$input['image']];
        AjaxImage::create($data);
        return response()->json([
            'success'   => 'Image Upload Successfully',
            'uploaded_image' => '<img src="/images/'.$input['image'].'" class="img-thumbnail" width="300" />',
            'class_name'  => 'alert-success'
            ]);
      }
    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 9 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="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 9 Ajax Image Upload with validation: Real Programmer</h1>
     <div class="alert" id="message" style="display: none"></div>

  <!-- <form action="{{ route('employeeImageUpload') }}" enctype="multipart/form-data" method="POST"> -->
     <form method="post" id="upload_form" enctype="multipart/form-data">
    @csrf
      	<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>
     <span id="uploaded_image"></span>

</div>
<script>
$(document).ready(function(){

 $('#upload_form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"{{ url('employeeImageUpload') }}",
   method:"POST",
   data:new FormData(this),
   dataType:'JSON',
   contentType: false,
   cache: false,
   processData: false,
   success:function(data)
   {
    $('#message').css('display', 'block');
    $('#message').html(data.success);
    $('#message').addClass(data.class_name);
    $('#uploaded_image').html(data.uploaded_image);
   }
  })
 });

});
</script>

</html>

Now you can open bellow URL on your browser:

php artisan serve

Git: https://github.com/siddharth018/laravel8ajaximage

Write A Comment