Laravel 5.4 sorting

21,299

The orderBy method allows you to sort the result of the query by a given column. The first argument to the orderBy method should be the column you wish to sort by, while the second argument controls the direction of the sort and may be either asc or desc, check the example:

$users = DB::table('table')
->orderBy('name', 'desc')  // You can pass as many columns as you want
->get();
Share:
21,299
VMeijer
Author by

VMeijer

Updated on July 09, 2022

Comments

  • VMeijer
    VMeijer almost 2 years

    I've got 2 columns, Model and Action. First thing I would like to achieve is to order the model from A to Z.

    I'm doing that with

    orderBy('model', 'ASC')
    

    Then I would like to order the action column on index, create, store etc. I've got a query, and i'me trying to sort the results in order: index, create, store, show, edit, update, destroy, [everything else].

    However the result i'm getting is: [everything else], index, create, store, show, edit, update, destroy

    Query:

    Permission::orderBy('model', 'ASC')->orderByRaw("FIELD(action, 'index', 'create', 'store', 'show', 'edit', 'update', 'destroy')")->get();
    

    Result should be something like:

    • model 1, index
    • model 1, create
    • model 1, store
    • etc
    • model 1, everything else
    • model 2, index
    • model 2, create
    • model 2, store
    • etc
    • model 2, everything else

    Has anyone got an idea how I can fix this?

    Thanks