Laravel 7/6 Ajax Image Upload With Intervention Package

10-Apr-2023

.

Admin

Hi Dev,

Today, I will learn you how to store file with Intervention Package in laravel 6. In This blog shows you how you can upload the image into the database and folder with example

we upload the image into the folder and store into database using jquery ajax in laravel 6 application.

We will Follow the bellow step.

Step 1 : Install Laravel project


In this step you can install fresh laravel project to using bellow command.

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

Step 2 : Install Image Intervention Package

Now We need to install the laravel image intervention package for resizing the image size. use the below command and install it.

composer require intervention/image

After successfully install a laravel image intervention package. Register image intervention package to providers and aliases go to app/config/app.php register here.

'providers' => [

Intervention\Image\ImageServiceProvider::class

],

'aliases' => [

'Image' => Intervention\Image\Facades\Image::class

]

Step 3 : Create Migration & Model

Now you will bellow command to create migration and model in laravel app.

php artisan make:model Photo -m

Above command to create one table migration file and one model file.

database/migrations/2019_12_11_111847_create_photos_table.php

<?php

use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;

class CreatePhotosTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('photos', function (Blueprint $table) {

$table->increments('id');

$table->string('photo_name');

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('photos');

}

}

Bellow command to use migrate your table.

php artisan migrate

Step 4 : Create Controller

In this step create controler file to use bellow command.

php artisan make:controller ImageController

Step 5 : Create Controller method

Create controller after you can put the bellow code in controller file.

app/http/controllers/ImageController

<?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 create()

{

return view('image');

}

public function store(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);

}

}

Step 6 : Create Routes

In this step you will create route in web.php file.

routes/web.php

Route::get('image','ImageController@create')->name('image.create');

Route::post('save-image','ImageController@store')->name('image.store');

Step 7 : Create View File

In this step you can create blade file in laravel app.

resources/views/create.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 Using Intervention Package Example - 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 5.7 Ajax Image Upload Using Intervention Package Example - <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>

</div>

</form>

</div>

</div>

</div>

<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: "{{ route('photo.store') }}",

data:formData,

cache:false,

contentType: false,

processData: false,

success:function(response){

$('#original').attr('src', 'public/images/'+ response.image);

$('#thumbImg').attr('src', 'public/thumbnail/'+ response.image);

},

error: function(data){

console.log(data);

}

});

}));

});

</script>

</body>

</html>

It will help you...

#Laravel 7

#Laravel

#Laravel 6