Last active
March 25, 2024 09:01
-
-
Save ajaxray/4cbe27cfaba4cc3ac6c47893e41989c5 to your computer and use it in GitHub Desktop.
[Laravel] Sorting Media Collection of Spacie Media Library by a custom property.
This file contains hidden or 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 | |
namespace App\Services; | |
use Illuminate\Support\Collection; | |
use Spatie\MediaLibrary\HasMedia; | |
use Spatie\MediaLibrary\MediaCollections\Models\Media; | |
class MediaPropertyService | |
{ | |
public function __construct( | |
private readonly HasMedia $subject, | |
private readonly string $collectionName = 'default', | |
) | |
{ | |
// | |
} | |
public function getSortedBy(string $customProperty): Collection | |
{ | |
return Media::query() | |
->where('model_type', '=', $this->subject::class) | |
->where('model_id', '=', $this->subject->id) | |
->where('collection_name', '=', $this->collectionName) | |
->orderByRaw("JSON_EXTRACT(custom_properties, \"$.{$customProperty}\") ASC") | |
->get(); | |
} | |
public function getSortedUrlsBy(string $customProperty): Collection | |
{ | |
return $this->getSortedBy($customProperty) | |
->map(fn($item) => $item->getUrl()); | |
} | |
public function getSortedPathsBy(string $customProperty): Collection | |
{ | |
return $this->getSortedBy($customProperty) | |
->map(fn($item) => $item->getPath()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment