I am creating real time chat system with laravel. I want to get lastest message from the db. I want query like this from eloquent.
$senderLastMessage = Message::where('sender_id',$user->id)->where('receiver_id',auth()->user()->id)->latest('created_at')->first(); $receiverLastMessage = Message::where('receiver_id',$user->id)->where('sender_id',auth()->user()->id)->latest('created_at')->first();
Now i want the lastest msg in this case the lastest msg will either be send from auth->user or from other user. how can i get this? if i get these seperately. i will have to create date comparisons like check date of senderLastMessage->created_at is greater or receiverLastMessage->created_at is greater or if they are equal then get there time and check whose time is greater and then display that message instance.
How can i get this from eloquent?
Advertisement
Answer
just use OR condition with some parenthesis in your query
$lastMessage = Message::where( fuunction($query) use($user) { $query->where('sender_id',$user->id) ->orWhere('receiver_id', $user->id); })->where( function($query) { $query->where('sender_id',auth()->id()) ->orWhere('receiver_id', auth()->id()); })->latest('created_at')->first();