Laravel 6 Ajax Image Upload Tutorial Example From Scratch

Laravel 6 Ajax Image Upload Tutorial Example From Scratch

New Laravel 6 ajax image upload with preview tutorial. This tutorial shows you how you can upload the image into the database and folder with example and live demo.

Before we upload the image into the folder and MySQL database using jquery ajax in laravel application, we will show the preview of the image. And also validate image using jquery before uploading into the server.

Here you can learn how to validate image on server-side and client-side validation. We will upload the image using jquery ajax without page refresh and reload.

Ajax Image Upload Laravel Tutorial

Just follow the below steps, upload the image with preview using the ajax and jQuery validation:

  • Install Laravel Fresh App
  • Setup Database
  • Install Image Intervention Package
  • Generate migration file and model
  • Make Route
  • Create Controller & Methods
  • Create Blade View
  • Make Folder
  • Run Development Server
  • Conclusion

1). Install Laravel Fresh App

First, we need to download laravel fresh new setup. Use the below command and download fresh new laravel setup :

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

2). Setup Database

After successfully install laravel Application, Go to your project .env file and set up database credential and move next step :

 DB_CONNECTION=mysql 
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here

3). Generate Migration & Model

Now we will create table name Photo and it’s migration file. use the below command :

php artisan make:model Photo -m

It command will create one model name Photo and also create one migration file for Photo table. After successfully run the command go to database/migrations file and replace function, below here :

public function up()
{
Schema::create('photos', function (Blueprint $table) {
$table->increments('id');
$table->string('photo_name');
$table->timestamps();
});
}

Before we run php artisan migrate command go to app/providers/AppServiceProvider.php and put the below code :

...
use Illuminate\Support\Facades\Schema;
 
....
function boot()
{
    Schema::defaultStringLength(191);
}
...

Next migrate the table using the below command :

php artisan migrate

4). Make Route

We will create two routes in web.php file. Go to app/routes/web.php file and create two below routes here :

 Route::get('photo', '[email protected]');
Route::post('save-photo', '[email protected]');

5). Create Controller

We need to create a controller name ImageController. Use the below command and create Controller :

php artisan make:controller ImageController

After successfully create controller go to app/controllers/ImageController.php and put the below code :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator,Redirect,Response,File;
Use Image;
Use App\Photo;
use Intervention\Image\Exception\NotReadableException;


class ImageController extends Controller
{

public function index()
{
  return view('image');
}

public function save(Request $request)
{
 request()->validate([
      'photo_name' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
 ]);

 if ($files = $request->file('photo_name')) {
    
    // for save original image
    $ImageUpload = Image::make($files);
    $originalPath = 'public/images/';
    $ImageUpload->save($originalPath.time().$files->getClientOriginalName());
    
    // for save thumnail image
    $thumbnailPath = 'public/thumbnail/';
    $ImageUpload->resize(250,125);
    $ImageUpload = $ImageUpload->save($thumbnailPath.time().$files->getClientOriginalName());

  $photo = new Photo();
  $photo->photo_name = time().$files->getClientOriginalName();
  $photo->save();
  }

  $image = Photo::latest()->first(['photo_name']);
  return Response()->json($image);


}
}

6). Create Blade view

In this step we need to create blade view file. Go to app/resources/views and create one file name image.blade.php :

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel Ajax Image Upload Tutorial - Tutsmake.com</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<style>
.avatar-pic {
width: 300px;
}
</style>
</head>
<body>
<div class="container">
<h3 style="margin-top: 12px;" class="text-center alert alert-success">Laravel Ajax Image Upload Tutorial - <a href="https://www.tutsmake.com" target="_blank">TutsMake</a></h3>
<br>
<div class="row justify-content-center">
<div class="col-md-8">
<form id="imageUploadForm" action="javascript:void(0)" enctype="multipart/form-data">
<div class="file-field">
<div class="row">
<div class=" col-md-8 mb-4">
<img id="original" src="" class=" z-depth-1-half avatar-pic" alt="">
<div class="d-flex justify-content-center mt-3">
<div class="btn btn-mdb-color btn-rounded float-left">
<input type="file" name="photo_name" id="photo_name" required=""> <br>
<button type="submit" class="btn btn-secondary d-flex justify-content-center mt-3">submit</button>
</div>
</div>
</div>
<div class=" col-md-4 mb-4">
<img id="thumbImg" src="" class=" z-depth-1-half thumb-pic"
alt="">
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>

Now we will implement laravel ajax image upload script, put the below script after closing of body tag.

<script>

$(document).ready(function (e) {

$('#imageUploadForm').on('submit',(function(e) {

$.ajaxSetup({

headers: {

  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

}

});

e.preventDefault();

var formData = new FormData(this);



$.ajax({

   type:'POST',

   url: "{{ url('save-photo')}}",

   data:formData,

   cache:false,

   contentType: false,

   processData: false,

   success:function(data){

       $('#original').attr('src', 'public/images/'+ data.photo_name);

   },

   error: function(data){

       console.log(data);

   }

});

}));

});

</script> 

7). Make Folder

Now create one folder name images where we store our images :

Go to public folder 
=> first create folder name images

8). Run Development Server

In this step, we will use the php artisan serve command. It will start your server locally

 php artisan serve
If you want to run the project diffrent port so use this below command
php artisan serve --port=8080

Now we are ready to run our example so run bellow command to quick run.

http://127.0.0.1:8000/photo
Or
http://localhost/blog/public/photo

If you want to remove public or public/index.php from URL In laravel, Click Me

Conclusion

In this laravel ajax image upload example, we have successfully uploaded image into datatabase and folder and we have successfully image upload without page refresh and reload using ajax.

If you have any questions or thoughts to share, use the comment form below to reach us.

Leave a Reply

Your email address will not be published. Required fields are marked *