PHPackages                             mihai-valentin/laravel-order-by-field - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. mihai-valentin/laravel-order-by-field

ActiveLibrary[Database &amp; ORM](/categories/database)

mihai-valentin/laravel-order-by-field
=====================================

A simple Laravel `Query\\Builder` extension that adds MySQL-like "order by field" feature

v1.2.0(3y ago)315.2k↓33.3%1MITPHPPHP ^8.0CI passing

Since Jan 16Pushed 1y ago1 watchersCompare

[ Source](https://github.com/mihai-valentin/laravel-order-by-field)[ Packagist](https://packagist.org/packages/mihai-valentin/laravel-order-by-field)[ RSS](/packages/mihai-valentin-laravel-order-by-field/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (6)Versions (5)Used By (0)

Laravel Order By Field
======================

[](#laravel-order-by-field)

This package provides a few Laravel `Query\Buider` marco in order to implement MySQL-like `order by filed(...)` feature.

Installation
------------

[](#installation)

Get the package

```
composer require mihai-valentin/laravel-order-by-field
```

Usage
-----

[](#usage)

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

How it works
------------

[](#how-it-works)

For the MySQL macro will generate a native `order by field(...)` expression. For all other drivers order clause will be implemented using `case` predicate.

### Using MySQL

[](#using-mysql)

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

### Using Postgresql, Sqlite

[](#using-postgresql-sqlite)

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

PhpStorm autocomplete
---------------------

[](#phpstorm-autocomplete)

You can create an `_ide_helper` file to tell your IDE about new methods. The helper file can look like this

```
