Sort items from a Collection from a predefined value

4

I have a Collection of Eloquent and would like to sort it by two fields at the same time being one of them a predefined value.

Ex: this Collection has several objects of type Categoria and I want to sort it so that categories with property slug equal "solicitacoes" are at the beginning and I want the rest to be in alphabetical order.

I know that the sort method can get a callback to sort the collection and tried to do (among other things) this

$sorted = $categorias->sort(function ($item, $next) {
    return $item->slug === 'solicitacoes' ? -1 :            
           strcmp($item->descricao, $next->descricao);
});

But the ordering worked very well, disregarding the categories with slug = "solicitacoes" was in alphabetical order, the problem is that the aforementioned were not in the beginning.

    
asked by anonymous 18.07.2017 / 16:42

2 answers

3

Using Collection , I override the sort method with SortBy .

The sortBy method internally causes Laravel to compare the values according to the types, through sort (something like that you did in the question using sort ).

So, we can check in sortBy if the value of slug is equivalent to "solicitações" . If so, we return NULL for this item to be placed above. Otherwise, we return "descricao" to sort by this field.

See:

$sorted = $categorias->sortBy(function ($item)
{
     return $item->slug === 'solicitacoes' ? null : $item->descricao;
});
    
18.07.2017 / 19:12
1

With the method sort and your rule has no way, what should be done is a where and then a union excluding:

$sort = $categorias->where('slug', 'solicitacoes')
            ->sortBy('descricao')
            ->union($categorias->where('slug','<>', 'solicitacoes')->sortBy('descricao'))
            ->all();

18.07.2017 / 18:56