-
app/Models/User.php
Open in GitHubuse Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { // public function userChats() { return $this->belongsToMany(Chat::class, ChatMember::class, 'user_id', 'chat_id')->withPivot('latest_read_msg'); } // public function totalUnreadMessages(){ $count = 0; $userChats = $this->userChats; foreach($userChats as $chat){ $latestReadMsgId = $chat->pivot->latest_read_msg; $count += $chat->chatMessages()->where('id', '>', $latestReadMsgId)->count(); } return $count; } }
-
master/routes/api.php
Open in GitHubuse Illuminate\Support\Facades\Route; Route::middleware('auth:sanctum')->get('/user', function (Request $request) { // add unread messages count to user object $user = $request->user(); $user->unreadMsgCount = $user->totalUnreadMessages(); return $user; }); //