Search code examples
phplaravellaravel-5eloquentlaravel-collection

Laravel collection order similar to DB FIELD


I have a query with following order

$query->orderByRaw("FIELD(type, 'red', 'green', 'aqua') ASC");

This will order items not alphabetically, but specifically by the value.

Is there is a way to do same thing in Laravel collection?

Like:

$collection = collect(`Items from DB`);

$final = $collection->sortBy(function($item){
    return $item->color == 'red'
});

Solution

  • Found a solution:

    $collection = collect(`Items from DB`);
    
    $final = $collection->sortBy(function($model){
        return array_search($model->color, ['red', 'green', 'aqua']);
    });
    

    array_search return item position (key), so if model color is red the key is 0 and so on. and this will order it.

    If there is other solutions (maybe faster) please post them, thank you.