trypost/app/Models/Traits/HasWorkspace.php

55 lines
1.3 KiB
PHP
Raw Normal View History

2026-01-19 00:49:13 +00:00
<?php
declare(strict_types=1);
2026-01-19 00:49:13 +00:00
namespace App\Models\Traits;
use App\Models\Workspace;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
trait HasWorkspace
{
/**
2026-01-20 19:53:54 +00:00
* Get all workspaces the user belongs to (as owner or member).
2026-01-19 00:49:13 +00:00
*/
2026-01-20 19:53:54 +00:00
public function workspaces(): BelongsToMany
2026-01-19 00:49:13 +00:00
{
2026-01-20 19:53:54 +00:00
return $this->belongsToMany(Workspace::class, 'user_workspace')
2026-01-19 00:49:13 +00:00
->withPivot('role')
->withTimestamps();
}
/**
* Get the user's current workspace.
*/
public function currentWorkspace(): BelongsTo
{
return $this->belongsTo(Workspace::class, 'current_workspace_id');
}
/**
* Switch to a different workspace.
*/
public function switchWorkspace(Workspace $workspace): void
{
$this->update(['current_workspace_id' => $workspace->id]);
}
/**
* Check if user belongs to a workspace (owner or member).
*/
public function belongsToWorkspace(Workspace $workspace): bool
{
2026-01-20 19:53:54 +00:00
return $this->workspaces()->where('workspaces.id', $workspace->id)->exists();
2026-01-19 00:49:13 +00:00
}
/**
* Get the count of workspaces the user owns.
*/
public function ownedWorkspacesCount(): int
{
return Workspace::where('user_id', $this->id)->count();
2026-01-19 00:49:13 +00:00
}
}