Skip to content

Instantly share code, notes, and snippets.

@royteusink
Last active June 17, 2024 13:45
Show Gist options
  • Save royteusink/d953539db903a6f97de36b2de99fcfbf to your computer and use it in GitHub Desktop.
Save royteusink/d953539db903a6f97de36b2de99fcfbf to your computer and use it in GitHub Desktop.
Laravel ScopeWhereInSequence

App/Traits/ScopeWhereInSequence.php

<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;

trait ScopeWhereInSequence
{
    public function scopeWhereInSequence(Builder $query, string $field, Collection|array $values): Builder
    {
        if ($values instanceof Collection) {
            $values = $values->toArray();
        }

        $query = $query->whereIn($field, $values);

        if (! empty($values)) {
            $query->orderByRaw('FIELD(' . $field . ', ' . implode(',', array_map('intval', $values)) . ')');
        }

        return $query;
    }
}

Setup:

use App\Traits\ScopeWhereInSequence;

class Article extends Model {
  use ScopeWhereInSequence;
}

Usage

Article::whereInSequence('id', [3,2,1])->get(); // Returned collection of articles is in order 3,2,1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment