Skip to content
Advertisement

Laravel Query Sending Different Result For Same Problem

Hi I am trying to create a one on one messaging system on LARAVEL. It was working all fine until for some users it started showing different result then expected. And it happens only for some users.. What is wrong with this query

$id =$receiver->id;
$messages = Message::where(function ($query) use ($id) {
        $query->where('user_id', '=', Auth::user()->id)
              ->where('receiver_id', '=', $id);
        })->orWhere(function ($query) use ($id) {
            $query->where('user_id', '=', $id)
                ->where('receiver_id', '=', Auth::user()->id);
        })->get();

After I return $messages the result is like this…

Working Result: Messages are coming sequentially..

Working Result

In View It shows like this..

enter image description here

Same Query Bad Result

enter image description here

In the view you can see date are not aligned in order

enter image description here

I really can’t figure out what went wrong if you can help I would really appreciate..

Advertisement

Answer

Your date is casting as UTC with ISO-8601 format, but I think date is not related with your issue, if you are not ordering with timestamp.
I suggest you to use orderBy with id, it can solve your issue easily :

$messages = Message::where(function ($query) use ($id) {
        $query->where('user_id', '=', Auth::user()->id)
              ->where('receiver_id', '=', $id);
        })->orWhere(function ($query) use ($id) {
            $query->where('user_id', '=', $id)
                ->where('receiver_id', '=', Auth::user()->id);
        })
        ->orderBy('id', 'ASC')
        ->get();
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement