Created
April 5, 2024 20:43
-
-
Save godismyjudge95/cf81adf4cf1de216437141a65f0dbeaa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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