4
I have a Collection of the Eloquent and I would like to order it through two fields at the same time being one of them a predefined value.
Ex.: this one Collection has several objects of the type Categoria and I want to order it so that the categories that have the property slug equal to "solicitacoes" stay at the beginning and I want the others to be in alphabetical order.
I know the method sort may receive 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 ordination did not work very well, disregarding the categories with slug = "solicitacoes" was in alphabetical order, the problem is that the aforementioned ones were not in the beginning.
strcmpreturns the difference of the characters in what differs. Examplestrcmpof"A"for"Z"return-25. I’d advise you to experiment with-100to stay before all.– Isac
@Isac I tried with
-10000and gave in the same.– Jéf Bueno
@Djalmamanfrin I didn’t understand a word you meant.
– Jéf Bueno
If you pass the sorted data alphabetically to the
collectionand then use the$sorted = $categorias->sortBy('solicitacoes'), which result would come out ofcollection $categorias? I started again because I couldn’t change the previous comment.– DNick
@Djalmamanfrin There is no
sortBy('solicitacoes')sincesolicitacoesis a value ofslug. If I understand correctly you want me to bring the results of the bank already ordered alphabetically and then try to do my custom ordering, if that’s it, it doesn’t work because the second ordering undoes the first.– Jéf Bueno
And
dd($item->slug)presents what ? for a request– Isac
@Isac Displays the field value
slug. Maysolicitacoes,downloads, anything. To be a request the field returnssolicitacoes.– Jéf Bueno
My question was more to make sure you’re getting into
ifand return-1/-10000for requests, do not have any space or odd character that makes the condition not enter, or until it is of a different type once it is being used===– Isac
Oh yes, he’s right. No strange character or anything.
– Jéf Bueno