Spatie MediaLibrary: Resize Original Uploaded Image to Save Disk Space
Founder of QuickAdminPanel
Inside of QuickAdminPanel, we’re using popular Spatie Medialibrary package to store media files. By default, it doesn’t do any transformation to the original uploaded file, but it’s very easy to change.
Typical example for this is when you don’t want to store the original image with its big size, and want to resize it to, let’s say, 1024×1024 pixels max.
In case of QuickAdminPanel, uploading files is done in two phases:
– First, file is actually uploaded to server using Dropzone.js and AJAX call to store the files;
– Next, when all form is submitted (see below), all uploaded files are assigned to Model with Spatie Medialibrary mentioned above.
More on the approach we take – in this article: Multiple File Upload with Dropzone.js and Laravel MediaLibrary Package
The package MediaLibrary doesn’t manipulate original image by default. Here’s the comment on their Github by creator Freek van Der Herten:
The medialibrary doesn’t make any changes to the original file. If you want to optimize the a file, you’ll have to do it yourself before adding it to the medialibrary.
So we need to resize the image before it’s used by the package.
The code example above will be for our QuickAdminPanel-generated code, but it will give you a picture of how it’s done, so you can probably adapt it to your Laravel project even if you’re not a user of our generator.
In our case, it’s in the trait file app/Http/Controllers/Traits/MediaUploadingTrait.php, this is the piece of code about upload – we’re uploading into storage/tmp/uploads folder:
$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 that uploaded image.
And the trick is that Spatie MediaLibrary is using their own package Spatie Image, which we can also use inside of our trait.
After the code above, add this:
Image::load($path . '/' . $name)->width(1024)->height(1024)->save();
Also, don’t forget to add this on top:
And, that’s it. Then uploaded file will be resized at that exact moment, and then in Controller’s store() method we just use that filename to assign it to Media Library:
$transaction = Transaction::create($request->all()); $transaction->addMedia(storage_path('tmp/uploads/' . $request->input('photo'))) ->toMediaCollection('photo');
Try our QuickAdminPanel Generator!
How it works:
1. Generate panel online
No coding required, you just choose menu items.
2. Download code & install locally
Install with simple "composer install" and "php artisan migrate".
3. Customize anything!
We give all the code, so you can change anything after download.