A very simple helper class that makes these tasks a walk in the park:
- replacing an old/existing file with a new one
- downsizing an image on upload
- deleting a file from a storage
- determining if a file is an image
Via composer:
composer require voerro/laravel-file-uploader
Add the FileUploaderServiceProvider
to the providers
array of your config/app.php
configuration file:
Voerro\FileUploader\FileUploaderServiceProvider::class,
Then add the Facade
to the aliases
array:
'FileUploader' => Voerro\FileUploader\FileUploaderFacade::class,
Import the FileUploader
class like this:
use Voerro\FileUploader\FileUploader;
Pass the uploaded file (an Illuminate\Http\UploadedFile
) instance to the make
method, then chain the upload
method, which will return the path to the newly stored file.
$path = FileUploader::make($file)->upload();
Initialization:
::make(Illuminate\Http\UploadedFile $file)
Deleting a file (the method checks if the file exists to eliminate possible errors):
::delete(string $filePath, string $storage = 'public')
Determine if a file is an image. Pass to the method an UploadedFile instance or a string with a path to the file:
::isImage($file, $storage = 'public')
->upload(string $path = '', string $storage = 'public')
Upload file under a specified name:
->uploadAs(string $filename, string $path = '', string $storage = 'public')
Replace an old file:
->replace(string $oldFilePath, string $path = '', string $storage = 'public')
Replace an old file, store the new file under a specified name:
->replaceAs(string $oldFilePath, string $newFilename, string $path = '', string $storage = 'public')
Downsize an image if it's bigger than the specified width and/or height (the aspect ratio will be saved). When called on a non-image file nothing would be happen, thus you don't need to manually check if the file is an image before deciding wether to call this method.
->downsize(integer $maxWidth, integer $maxHeight)
Crop and resize an image to fit the the specified dimensions (the same as ->fit()
from Intervention Image)
->fit(integer $width, integer $height, boolean $dontUpsize = false)
Call this method before calling any of the above methods, for example:
FileUploader::make($image)->downsize(200, 200)->replace('old_image_file.jpg');
This is open-sourced software licensed under the MIT license.