Skip to content

Instantly share code, notes, and snippets.

@godismyjudge95
Created April 5, 2024 20:43
Show Gist options
  • Save godismyjudge95/cf81adf4cf1de216437141a65f0dbeaa to your computer and use it in GitHub Desktop.
Save godismyjudge95/cf81adf4cf1de216437141a65f0dbeaa to your computer and use it in GitHub Desktop.
<?php
namespace App\Models\Traits;
use Illuminate\Contracts\Database\Eloquent\Builder;
trait OrderByArrayScope
{
public function scopeOrderByArray(Builder $query, string $key, array $values, string $direction = 'ASC', bool $prefix = true)
{
$index = count($values);
$cases = collect($values)
->map(function ($value, $index) use ($key, $prefix) {
if ($prefix && !str($key)->contains('.')) {
$key = $this->getTable() . '.' . $key;
}
$value = $value?->value ?? $value;
return "WHEN {$key} = '{$value}' THEN {$index}";
})
->implode("\n ");
$query->orderByRaw(<<<SQL
CASE
{$cases}
ELSE {$index}
END
{$direction}
SQL);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment