So you want to upload an image and resize it with laravel 5.7 and above, it's gonna be very easy all we are gonna do is to require our famous library Intervention Image.
Instalation and Configuration
please make sure to install it in your laravel application just copy and past this line in your terminal.
composer require intervention/image
After that go to your app/config.php
file and add those two lines to your providers and alias arrays.
$provides => [
'Intervention\Image\ImageServiceProvider'
],
$aliases => [
'Image' => 'Intervention\Image\Facades\Image'
]
One thing is important is that since we are going to upload images to our storage folder and not in public folder, we have to create symbolic link to storage folder, by running this command again:
php artisan storage:link
Right now go to your storage/app/public/
and create two folders there images
and posts_thumbs
.
If you have done all that, you are good to go, and start the good stuffs.
Adding Route and Controller
I assume you have created your own controller if not just run this command again
php artisan make:controller MediaController
After that checkout your web.php
file and create your routes
Route::get('/images','MediaController@index')->name('images');
Route::post('/upload','MediaController@upload')->name('upload');
Next step is to go and create two functions in our MediaController
so here is it
<?php
namespace App\Http\Controllers\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Image;
class MediaController extends Controller
{
public function index(){
return view('images');
}
public function upload(Request $request){
if ($request->ajax()) {
$this->validate($request, [
'file' => 'image|required|mimes:jpeg,png,jpg,gif,svg'
]);
$file = $request->file('file');
$fileSize = round(($request->file('file')->getClientSize() / 1024), 2);
$fileNameWithExtension = $file->getClientOriginalName();
$fileNameWithoutExtension = pathinfo($fileNameWithExtension, PATHINFO_FILENAME);
$extention = $file->getClientOriginalExtension();
$fileNameToStored = $fileNameWithoutExtension.'_'.time().'.'.$extention;
//store the original image as it is
$request->file('file')->storeAs('public/images', $fileNameToStored);
//resize the images
$thumb_size = 200;
$thumbnailPath = storage_path('app/public/posts_thumbs/'.$fileNameToStored);
$img = Image::make($file)
->resize($thumb_size,$thumb_size)
->save($thumbnailPath);
return response()->json([
'data' => [
'savedName' => $fileNameToStored,
'fileSize' => $fileSize,
'uploaded' => true,
'status' => "Image Uploaded Successfully"
]
]);
}
}
Adding View File and Ajax Code
After creating your controller now it's time to create a blade
file in your views
folder images.blade.php
inside that file you will see some jquery and javascript code that's what will allow us to upload the image to the storage folder in our two folders that we have created before.
you will need jquery for this, make sure to download it.
Here is our blade
file
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Upload Image with Ajax and Intervention Image Library</title>
</head>
<body>
<form id="upload" action="{{ route('upload') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file" />
<input type="submit" value="Upload" class="button" />
</form>
<script src="{{asset('js/jquery-3.2.1.min.js') }}"></script>
<script>
$(function(){
$('#upload').on('submit', function(evt){
evt.preventDefault();
var myFileInput = $("input[name=file]");
if ($("input[name=file]") != 'undefined')
{
$.ajax({
dataType: 'json',
async:false,
type:'POST',
url: $(this).attr('action'),
processData: false,
contentType: false,
data: new FormData($(".form-upload-images")[0])
})
.done(function(data){
if (data.data.uploaded) {
console.log(data.data.status);
}else{
console.log("image was not uploaded");
}
}).fail(function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " errorThrown );
console.log( "Status: " status );
console.dir( xhr.responseText);
}).always(function() {
}); //end ajax
}
});
})
</script>
</body>
</html>
You can access your image by using<img src="/storage/images/YourImageName" />
or your thumbnail <img src="/storage/posts_thumbs/YourImageName" />
.
Conclusion
That's how I upload my images and you still can do much more modifications and optimizations in this code, this is just the basics, so go and make your own coding style, I hope this article help you understand how to upload and image with ajax and laravel 5.7 and above and also resize that image with Intervention Image Library.