Skip to content

Instantly share code, notes, and snippets.

@ajaxray
Last active March 25, 2024 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajaxray/4cbe27cfaba4cc3ac6c47893e41989c5 to your computer and use it in GitHub Desktop.
Save ajaxray/4cbe27cfaba4cc3ac6c47893e41989c5 to your computer and use it in GitHub Desktop.
[Laravel] Sorting Media Collection of Spacie Media Library by a custom property.
<?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