Last active
September 21, 2022 21:29
-
-
Save KABBOUCHI/1c8300fb2e9e3d229e229a968fa01b7d to your computer and use it in GitHub Desktop.
Laravel UploadedFile macro for image manipulation using Intervention Image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
{ | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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() | |
{ | |
// | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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