Skip to content

Instantly share code, notes, and snippets.

@Giacomo92
Forked from andreshg112/OrderByField.php
Created October 16, 2019 17:17
Show Gist options
  • Save Giacomo92/b31d2a3702569d67449a053a16b0d596 to your computer and use it in GitHub Desktop.
Save Giacomo92/b31d2a3702569d67449a053a16b0d596 to your computer and use it in GitHub Desktop.
It can be used for queries like this in MySQL: `SELECT * FROM `plans` ORDER BY FIELD(`interval`, 'day', 'week', 'month', 'year');`
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
/**
* Traits that eases the use of ORDER BY FIELD with an eloquent model.
* https://github.com/laravel/ideas/issues/1066
*/
trait OrderByField
{
public function scopeOrderByField(Builder $query, string $field, array $values)
{
$orderedValues = implode(', ', $values);
return $query->orderByRaw(DB::raw("FIELD({$field}, {$orderedValues})"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment