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