Y
Y
Yuri Kulaxyz2019-09-21 23:05:53
PHP
Yuri Kulaxyz, 2019-09-21 23:05:53

Why doesn't Laravel sort() work?

It is necessary to display dialogs, while the essence of chats, as such, is not present. There are just messages in which sender_id and receiver_id. Now you need to display a list of chats. Then I came across a problem that it is not possible to sort users by the latest message, tell me what is wrong with the code?

$users = $users->sort(function ($user){
            return $user->lastMessage->created_at->toDateTimeString();
        });

Displays generally in the left order, there is no dependence on the date of the last message.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Y
Yan-s, 2018-05-07
@smoln

Of course you can. You do a nested iteration of arrays through foreach or whatever is more convenient for you. Add the check if field_with_brand_name === Ferroz to the enumeration, if true, then add the data to the resulting array.

A
Alex Wells, 2019-09-22
@Alex_Wells

->sortByDesc('lastMessage.created_at')
?

V
Victor, 2019-09-23
@v_decadence

Because you need to pass a callback to the sort function by analogy with the uasort PHP function, there are some peculiarities there.
You need to use sortBy / sortByDesc.
https://github.com/laravel/framework/blob/6.x/src/...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question