Skip to content

Instantly share code, notes, and snippets.

@itsnunolemos
Created June 8, 2020 21:43
Show Gist options
  • Save itsnunolemos/3f3527abfa30c47e59c32673649099da to your computer and use it in GitHub Desktop.
Save itsnunolemos/3f3527abfa30c47e59c32673649099da to your computer and use it in GitHub Desktop.
laravel-medialibrary MediaPathGenerator
<?php
// config/medialibrary.php
// Line 85
/*
* The class that contains the strategy for determining a media file's path.
*/
'path_generator' => App\Helpers\MediaPathGenerator::class,
<?php
// app/Http/Helpers/MediaPathGenerator.php
namespace App\Helpers;
use Spatie\MediaLibrary\Models\Media;
use Spatie\MediaLibrary\PathGenerator\PathGenerator;
class MediaPathGenerator implements PathGenerator
{
public function getPath(Media $media) : string
{
return class_basename($media->model_type).'/'.$media->model_id.'/'.$media->getKey().'/';
}
public function getPathForConversions(Media $media) : string
{
return $this->getPath($media).'conversions/';
}
public function getPathForResponsiveImages(Media $media): string
{
return $this->getPath($media).'responsive/';
}
}
<?php
// app/User.php
public function registerMediaCollections()
{
$this
->addMediaCollection('avatar')
->useFallbackUrl('/images/default.jpg')
->useFallbackPath(public_path('images/default.jpg'))
->singleFile();
}
public function registerMediaConversions(Media $media = null)
{
$this->addMediaConversion('thumb')
->fit('crop', 150, 150);
$this->addMediaConversion('small')
->fit('crop', 346, 346)
->performOnCollections('avatar')
->nonQueued();
$this->addMediaConversion('medium')
->fit('crop', 500, 500)
->performOnCollections('avatar');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment