Created
June 8, 2020 21:43
-
-
Save itsnunolemos/3f3527abfa30c47e59c32673649099da to your computer and use it in GitHub Desktop.
laravel-medialibrary MediaPathGenerator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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, |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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/'; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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