Inside QuickAdminPanel, we use the popular Spatie Medialibrary package to store media files. By default, it does not perform any transformation of the original uploaded file, but it is very easy to modify it.
A typical example is when you don’t want to store the original image with its large size and want to resize it to, say, 1024 × 1024 pixels maximum.
In the case of QuickAdminPanel, the downloading of files is done in two phases:
– First, the file is actually downloaded to the server using Dropzone.js and AJAX call to store files;
– Then, when all forms are submitted (see below), all uploaded files are assigned model with Spatie Medialibrary mentioned above.
Learn more about the approach we take – in this article: Multiple File Upload with Dropzone.js and the Laravel MediaLibrary Package
The MediaLibrary package does not manipulate the original image by default. Here is the comment on their Github from creator Freek van Der Herten:
The media library does not make any changes to the original file. If you want to optimize a file, you will need to do it yourself before adding it to the media library.
So we need to resize the image Before it is used by the package.
The code example above will be for our QuickAdminPanel generated code, but it will give you a picture of how this is done, so you can probably adapt it to your Laravel project even if you are not a user of our generator.
In our case, it’s in the traits file app/Http/Controllers/Traits/MediaUploadingTrait.phphere is the piece of code regarding the download – we download in storage/tmp/downloads case:
$path = storage_path('tmp/uploads');
$file = $request->file('file');
$name = uniqid() . '_' . trim($file->getClientOriginalName());
$file->move($path, $name);
So this is exactly where we need to resize this uploaded image.
And the trick is that Spatie MediaLibrary uses its own Spatie Image package, which we can also use in our stroke.
After the code above, add this:
Image::load($path . '/' . $name)->width(1024)->height(1024)->save();
Also don’t forget to add this at the top:
use Spatie\Image\Image;
And that’s it. Then the downloaded file will be resized at that exact moment, then in the controller’s store() method we simply use this filename to assign it to the media library:
$transaction = Transaction::create($request->all());
$transaction->addMedia(storage_path('tmp/uploads/' . $request->input('photo')))
->toMediaCollection('photo');
Simple, right?