Skip to content

Instantly share code, notes, and snippets.

@andreshg112
Last active April 6, 2023 09:25
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save andreshg112/b359089878bdb2269321838d8921f429 to your computer and use it in GitHub Desktop.
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');`
<?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);
}
}
@andreshg112
Copy link
Author

Example:

$plans = Plan::orderByField('interval', ['day', 'week', 'month', 'year'])->get();

laravel/ideas#1066

@staudenmeir
Copy link

If you allow user input, this is vulnerable to SQL injections.

@markjaquith
Copy link

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