45 lines
1.2 KiB
PHP
45 lines
1.2 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;
|
|
}
|
|
|
|
// Candidates don't have a tenant_id but must access
|
|
// quizzes/job positions linked to their position
|
|
if ($user->role === 'candidate') {
|
|
return;
|
|
}
|
|
|
|
if ($user->tenant_id) {
|
|
$builder->where('tenant_id', $user->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);
|
|
}
|
|
}
|