Last active
April 6, 2023 09:25
-
-
Save andreshg112/b359089878bdb2269321838d8921f429 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; | |
/** | |
* Traits that eases the use of ORDER BY FIELD with an eloquent model. | |
* https://github.com/laravel/ideas/issues/1066 | |
*/ | |
trait OrderByField | |
{ | |
/** | |
* Scope orderByField(string $field, array $values). | |
* | |
* @param \Illuminate\Database\Query\Builder $query | |
* @param string $field | |
* @param array $values | |
* @return \Illuminate\Database\Query\Builder | |
*/ | |
public function scopeOrderByField($query, string $field, array $values) | |
{ | |
if (empty($values)) { | |
return $query; | |
} | |
$placeholders = implode(', ', array_fill(0, count($values), '?')); | |
return $query->orderByRaw("FIELD({$field}, {$placeholders})", $values); | |
} | |
} |
If you allow user input, this is vulnerable to SQL injections.
public function scopeOrderByField(Builder $query, string $field, array $values)
{
$placeholders = implode(', ', array_fill(0, count($values), '?'));
return $query->orderByRaw(DB::raw("FIELD({$field}, {$placeholders})", $values));
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
laravel/ideas#1066