Skip to content

Instantly share code, notes, and snippets.

@ajaxray
Last active March 25, 2024 09:01
Show Gist options
  • Save ajaxray/4cbe27cfaba4cc3ac6c47893e41989c5 to your computer and use it in GitHub Desktop.
Save ajaxray/4cbe27cfaba4cc3ac6c47893e41989c5 to your computer and use it in GitHub Desktop.

Revisions

  1. ajaxray revised this gist Mar 25, 2024. No changes.
  2. ajaxray revised this gist Mar 25, 2024. No changes.
  3. ajaxray created this gist Mar 25, 2024.
    40 changes: 40 additions & 0 deletions MediaPropertyService.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    <?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());
    }
    }