-
-
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');`
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\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