This package provides a few Laravel Query\Buider
marco in order to implement MySQL-like order by filed(...)
feature.
Get the package
composer require mihai-valentin/laravel-order-by-field
use \Illuminate\Support\Facades\DB;
// Order records by a column asc
DB::table('table_name')->orderByField('column', ['first', 'second', 'third']);
// Order records by a column desc
DB::table('table_name')->orderByField('column', ['first', 'second', 'third'], 'desc');
DB::table('table_name')->orderByFieldDesc('column', ['first', 'second', 'third']);
For the MySQL macro will generate a native order by field(...)
expression. For all other drivers order clause will be
implemented using case
predicate.
use \Illuminate\Support\Facades\DB;
// Before
DB::table('table_name')->orderByRaw("field(`column`, 'first', 'second', 'third')");
// With macro
DB::table('table_name')->orderByField('column', ['first', 'second', 'third']);
use \Illuminate\Support\Facades\DB;
// Before
DB::table('table_name')->orderByRaw("
case
when \"column\"='first' then 1
when \"column\"='second' then 2
when \"column\"='third' then 3
else 0
end
");
// With macro
DB::table('table_name')->orderByField('column', ['first', 'second', 'third']);
You can create an _ide_helper
file to tell your IDE about new methods. The helper file can look like this
<?php
namespace Illuminate\Contracts\Database\Query {
use MihaiValentin\LaravelOrderByFiled\OrderByFieldServiceProvider;
/**
* @method Builder orderByField(string $column, array $order, string $direction = 'asc')
* @method Builder orderByFieldDesc(string $column, array $order)
*
* @see OrderByFieldServiceProvider
*/
interface Builder {}
}
namespace Illuminate\Database\Eloquent {
/**
* @method Builder orderByField(string $column, array $order, string $direction = 'asc')
* @method Builder orderByFieldDesc(string $column, array $order)
*
* @see OrderByFieldServiceProvider
*/
class Builder implements BuilderContract {}
}
You can find it here
You can run tests using the make
# Run tests, code static analysis and cs fixer
make test
# Run phpunit tests
make phpunit
You can build the package using the make
# Install composer dependencies and run tests
make
In order to ensure that the community is welcoming to all, please review and abide by the Code of Conduct.
Please see CONTRIBUTING.md for details.
The MIT License (MIT). Please see License File for more information.