Example of Pivot tables with extra fields in familytree365/backend

File app/Models/User.php (link to Github)
use 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;
    }
}
File master/routes/api.php (link to Github)
use 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;
});
//