1

I need to sort an array of objects in ascending order by ID called $messages, I tried many things but none seem to be working. Here is what I tried:

public function getMessagesPage(Request $request)
    {
        $user_id = $request->session()->get('id');

        $user_second = User::where('username', $request->username)->first();

        $messages_1 = Messages::where('user_1', $user_id, 'AND')->where('user_2', $user_second->id)->orderBy('id', 'asc')->get();
        $messages_2 = Messages::where('user_2', $user_id, 'AND')->where('user_1', $user_second->id)->orderBy('id', 'asc')->get();

        $messages = $messages_1->merge($messages_2);

        $messages = collect($messages);
        $messages->sortBy('id');

        return view('messages')->with('messages', $messages)->with('user_id', $user_id)->with('user_second', $user_second);
    }
0

2 Answers 2

1

You can sort your collection with sortBy() but remember that the function returns the collection sorted, doesn't mutate the original collection, so you have to change this line:

//$messages->sortBy('id');
$messages = $messages->sortBy('id');

As better alternative you can get all the messages sorted with only one query:

$messages = Messages::where([['user_1', $user_id], ['user_2', $user_second->id]])
               ->orWhere([['user_2', $user_id], ['user_1', $user_second->id]])
               ->orderBy('id', 'asc')
               ->get()

This is the same as writing this SQL:

select * from messages 
    where (user_1 = $user_id and user_2 = $user_second->id) 
    or (user_2 = $user_id and user_1 = $user_second->id) 
    order by id asc
Sign up to request clarification or add additional context in comments.

1 Comment

Please consider accepting and upvoting the answer if you find it useful
0

You could try

$messages_1 = Messages::where('user_1', $user_id)->where('user_2', $user_second->id)->orderBy('id', 'asc')->get();
$messages_2 = Messages::where('user_2', $user_id)->where('user_1', $user_second->id)->orderBy('id', 'asc')->get();

Remove the AND from the first WHERE. Eloquent knows that if you chain ->where() clauses, to use AND between them.

Alternatively, if you are using Laravel 5.3 or greater you can pass an array to in a where clause

$messages_1 = Messages::where([
     'user_1' => $user_id,
     'user_2' => $user_second->id])
->orderBy('id', 'asc')
->get();

Alternatively, if the following $messages = collect($messages); is correctly returning a Key / Value pair array, you should simply be able to use the following

return view('messages')
    ->with([
       'messages'    => sort($messages),
       'user_id'     => $user_id,
       'user_second' => $user_second
    ]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.