Laravel 7/6 Ajax Image Upload With Preview Example Tutorial

Laravel 7/6 Ajax Image Upload With Preview Example Tutorial

Laravel 7.x, 6.x ajax image upload with preview example tutorial. Here you will learn how to upload the image using jQuery ajax into the database and folder with preview example.

So this laravel ajax image file upload tutorial will guide on how to upload the image file into the folder and MySQL database using jquery ajax in laravel application. And as well as show preview of the image file before uploading the file into folder and mysql database in laravel.

As well as learn how to validate image file on server-side and client-side validation. Before uploading images using jquery ajax without page refresh and reload.

Laravel Ajax Image Upload with Preview Example Tutorial

Just follow the below steps and implement ajax image upload with preview and validation laravel app:

  • Install Laravel App
  • Setup Database
  • Create Image migration file and model
  • Add Route For Image
  • Create Controller & Methods
  • Create Blade View
  • Create Folder
  • Run Development Server

1). Install Laravel App

First of all, you need to download a laravel fresh new setup for laravel ajax image upload with preview app. So 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). Create Image migration file and model

In this step, you need to create a table name Photo and it’s migration file. So, run the following 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 you run php artisan migrate command go to app/providers/AppServiceProvider.php and add the below code into AppServiceProvider.php file:

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

Next, run the following command to migrate the tables into database:

php artisan migrate

4). Add Route For Image

Now, you need to add two routes in web.php file. Go to app/routes/ folder and open web.php file. Then add the following routes into web.php file:

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

5). Create Controller

In this step, you 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, you 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>

Here, implement laravel ajax image upload with preview script. So add the following script into image.blade.php file 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). Create Folder

Now create one folder name images ,where you store our images :

Go to public folder 
=> first create folder name images

8). Run Development Server

In this step, you need to run the php artisan serve command to start your laravel ajax upload image with preview app:

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

Now you 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

Laravel ajax image upload example, you have successfully uploaded image into datatabase and folder. And you have successfully image upload without page refresh and reload using ajax.

Recommended Laravel Tutorial

  1. Laravel Twitter Login Example Using Socialite Package
  2. Laravel Linkedin Login Tutorial With Live Demo
  3. Github Login in laravel with Example
  4. Laravel Socialite Google Login Example
  5. Laravel Multi Auth( Authentication) Example Tutorial
  6. Laravel Custom Login Registration Example Tutorial
  7. Laravel REST API (Login & Registration) Authentication

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

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