Laravel 8.x Ajax Image Upload With Preview

Hello Artisan 

Today, I am going to show you How to image or file upload using jquery Ajax in our Laravel application using base 64. I won't use image intervention before store it into database, but you can use it if you want.

In this laravel 8 jquery ajax Image upload tutorial i will show you how to upload image using ajax request.  Also we will see how to validate the image before uploading it into server.

When we upload the image instantly we will see our uploaded image. That mean we will see the preview of our uploaded image. We will upload the image using jquery ajax without page refresh and reload.

We can upload image using Ajax request in laravel 6 very easily. Let's start our laravel ajax image upload tutorial from scratch.

Table of Contents for Laravel Ajax Image Upload Tutorial

  • Install Laravel 
  • Create Route
  • Create Controller
  • Create Model and Migration
  • Create View
  • Make Storage Folder Public
  • See Output

 

Preview : After select a image before uploading

laravel-6-ajax-image-upload-with-preview

Preview : After hitting submit button

laravel-ajax-image-upload-base-64

 

Now let's start our laravel 6 ajax image upload tutorial with preview using base 64.

Step 1: Install Laravel

In first step to create laravel ajax image upload in laravel , if you haven't laravel 6 application setup then we have to get fresh laravel 6 application. 

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

 

Step 2: Create Model & Migration

Let’s create a Image model along with the migration file

php artisan make:model Image -m

 

Let’s now go ahead and modify the migration file to add the required columns.

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('image');
            $table->timestamps();
        });
    }

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

 

app/Image.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    protected $fillable = [
        'image'
    ];
}

 

Now run migrate command to create ajax jquery image upload in laravel.

php artisan migrate

 

Step 3: Create Route

In this is step we need to create two route one for render form view and second for add new image file. so open your routes/web.php file and add following route.

routes/web.php

Route::get('photo', 'ImageController@index');
Route::post('photo', 'ImageController@save');

 

Step 4: Create Controller

In this point, now we should create new controller call ImageController to create our two method for uploading image.

app/Http/Controllers/ImageController.php

namespace App\Http\Controllers;

use App\Image;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ImageController extends Controller
{
    public function index() {
        return view('image');
    }
 
    public function save(Request $request)
    {
        request()->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);
 
        if ($files = $request->file('image')) {
            
            $fileName =  "image-".time().'.'.$request->image->getClientOriginalExtension();
            $request->image->storeAs('image', $fileName);
            
            $image = new Image;
            $image->image = $fileName;
            $image->save();

            return Response()->json([
                "image" => $fileName
            ], Response::HTTP_OK);
 
        }
 
    }
}

 

Step 5:  Create View

In this step, we have to create blade file to see our form and upload image into database using ajax request.

resources/views/image.blade.php

 

Now paste this following code to your image.blade.php file before the end body tag.

$(document).ready(function (e) {
   
   $.ajaxSetup({
       headers: {
           'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
   });
  
   $('#image').change(function(){
           
    let reader = new FileReader();

    reader.onload = (e) => { 

      $('#image_preview_container').attr('src', e.target.result); 
    }

    reader.readAsDataURL(this.files[0]); 
  
   });
  
   $('#upload_image_form').submit(function(e) {

     e.preventDefault();
  
     var formData = new FormData(this);
  
     $.ajax({
        type:'POST',
        url: "{{ url('photo')}}",
        data: formData,
        cache:false,
        contentType: false,
        processData: false,
        success: (data) => {
           this.reset();
           alert('Image has been uploaded successfully');
        },
        error: function(data){
           console.log(data);
         }
       });
   });
});

 

Step 6 : Making Files Public

As you can notice current files are uploaded to the storage directory which is not public by default. It’s the Laravel’s default settings to hide default file upload from user’s as a security perspective.

You need to change following things. Open filesystems.php which is located under public directory. Change the default parameter from local to public.

config/filesystems.php

'default' => env('FILESYSTEM_DRIVER', 'public'),

 

And run the following command.

php artisan storage:link

 

Now you will find your uploaded image inside the following path

storage/app/public/image

Everything is done. Now you can open bellow urlon your browser:

http://localhost:8000/photo

 

Read also Laravel 6 Ajax CRUD Example with Sweet Alert

 

Now all are set to go. If you found this tutorial helpful and if you have any questions, Let me know in comments. Hope this Laravel ajax image upload tutorial will help you. 

 

#laravel #image-upload #file-upload #base64 #ajax #jquery #laravel-6 #client-side-validation #form-jquery #form-validation #post-ajax