Files
RecruIT/app/Traits/BelongsToTenant.php

48 lines
1.3 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(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);
}
}