Skip to content

Instantly share code, notes, and snippets.

@KABBOUCHI
Last active September 21, 2022 21:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save KABBOUCHI/1c8300fb2e9e3d229e229a968fa01b7d to your computer and use it in GitHub Desktop.
Save KABBOUCHI/1c8300fb2e9e3d229e229a968fa01b7d to your computer and use it in GitHub Desktop.
Laravel UploadedFile macro for image manipulation using Intervention Image
<?php
namespace {
exit("This file should not be included, only analyzed by your IDE");
}
namespace Illuminate\Http {
/**
* @package Illuminate\Http\UploadedFile
* @method UploadedFile manipulate(\Closure $callback)
*/
class UploadedFile
{
}
}
<?php
namespace App\Providers;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
use Intervention\Image\Facades\Image;
class UploadedFileServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
UploadedFile::macro('manipulate', function ($callback) {
return tap($this,function (UploadedFile $file) use ($callback) {
/** @var \Intervention\Image\Image $image */
$image = Image::make($file->getPathname());
$callback($image);
$image->save();
});
});
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
}
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Image;
class UserPhotoController extends Controller
{
public function update()
{
request()->validate([
'photo' => ['required', 'image']
]);
$user->update([
'photo' => request()
->file('photo')
->manipulate(function (Image $image){
$image->fit(400,400);
})
->storePublicly('avatars/users')
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment