1 | initial version |
To crop an image using Spatie Image and Spatie Laravel Media Library, you need to follow these steps:
Step 1: Install Spatie Image and Spatie Laravel Media Library via composer:
composer require spatie/laravel-medialibrary spatie/image
Step 2: Publish the configuration files:
php artisan vendor:publish --provider="Spatie\MediaLibrary\MediaLibraryServiceProvider" --tag="config"
php artisan vendor:publish --provider="Spatie\Image\ImageServiceProvider"
Step 3: Create a media model (for example, Image
) that uses the HasMediaTrait
:
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Spatie\MediaLibrary\HasMedia\HasMedia;
use Illuminate\Database\Eloquent\Model;
class Image extends Model implements HasMedia
{
use HasMediaTrait;
}
Step 4: Add the image
collection to the Image
model:
use Spatie\MediaLibrary\MediaCollections\Models\Collections\MediaCollection;
class Image extends Model implements HasMedia
{
use HasMediaTrait;
public function registerMediaCollections(): void
{
$this->addMediaCollection('image')
->registerMediaConversions(function (Media $media): void {
$this
->addMediaConversion('thumbnail')
->crop(Manipulations::CROP_CENTER, 100, 100);
$this
->addMediaConversion('large')
->crop(Manipulations::CROP_CENTER, 800, 600);
});
}
}
Here, we created two media conversions: thumbnail
and large
. Both of them will crop the image from its center. The thumbnail
conversion will have a size of 100x100 px, while the large
conversion will have a size of 800x600 px.
Step 5: In your controller, store the uploaded image and process it:
use Illuminate\Http\Request;
class ImageController extends Controller
{
public function store(Request $request)
{
$image = new Image;
$image->addMediaFromRequest('image')
->toMediaCollection('image');
return redirect()->back();
}
}
Here, we use the addMediaFromRequest
method to store the uploaded image and add it to the image
collection. Once the image is stored, the registered media conversions will be automatically applied.
Step 6: In your view, display the images using the img
tag and the getUrl
method:
@foreach($images as $image)
<img src="{{ $image->getUrl('thumbnail') }}" alt="">
@endforeach
Here, we use the getUrl
method to get the URL of the thumbnail
media conversion. You can also use other media conversions by passing their names as arguments to the getUrl
method.
That's it! Now you should be able to upload and crop images using Spatie Image and Spatie Laravel Media Library.