45 lines
1.4 KiB
PHP
45 lines
1.4 KiB
PHP
<?php
|
|
|
|
namespace App\Traits;
|
|
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Support\Facades\Auth;
|
|
|
|
trait BelongsToTenant
|
|
{
|
|
protected static function bootBelongsToTenant()
|
|
{
|
|
static::addGlobalScope('tenant', function (Builder $builder) {
|
|
if (Auth::check()) {
|
|
$user = Auth::user();
|
|
|
|
// Super admins see everything
|
|
if ($user->role === 'super_admin') {
|
|
return;
|
|
}
|
|
|
|
// All other users (admins and candidates) are filtered by their tenant.
|
|
// This includes candidates, who must only see data from their own organization.
|
|
// Resources with a null tenant_id are considered global and always visible.
|
|
if ($user->tenant_id) {
|
|
$builder->where(function ($query) use ($user) {
|
|
$query->where('tenant_id', $user->tenant_id)
|
|
->orWhereNull('tenant_id');
|
|
});
|
|
}
|
|
}
|
|
});
|
|
|
|
static::creating(function ($model) {
|
|
if (Auth::check() && Auth::user()->tenant_id && Auth::user()->role !== 'super_admin') {
|
|
$model->tenant_id = Auth::user()->tenant_id;
|
|
}
|
|
});
|
|
}
|
|
|
|
public function tenant()
|
|
{
|
|
return $this->belongsTo(\App\Models\Tenant::class);
|
|
}
|
|
}
|