47 lines
1.2 KiB
PHP
47 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Scopes;
|
|
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Scope;
|
|
use Illuminate\Support\Facades\Auth;
|
|
|
|
class CompanyScope implements Scope
|
|
{
|
|
public function apply(Builder $builder, Model $model): void
|
|
{
|
|
if (app()->runningInConsole() && !app()->runningUnitTests()) {
|
|
return;
|
|
}
|
|
|
|
if (!Auth::check()) {
|
|
return;
|
|
}
|
|
|
|
$user = Auth::user();
|
|
|
|
if ($user->type === 'superadmin') {
|
|
return;
|
|
}
|
|
|
|
$creatorId = in_array($user->type, ['company', 'superadmin'])
|
|
? $user->id
|
|
: $user->created_by;
|
|
|
|
$builder->where($model->getTable() . '.created_by', $creatorId);
|
|
}
|
|
|
|
public function extend(Builder $builder): void
|
|
{
|
|
$builder->macro('withoutCompanyScope', function (Builder $builder) {
|
|
return $builder->withoutGlobalScope(static::class);
|
|
});
|
|
|
|
$builder->macro('forCompany', function (Builder $builder, int $companyId) {
|
|
return $builder->withoutGlobalScope(static::class)
|
|
->where($builder->getModel()->getTable() . '.created_by', $companyId);
|
|
});
|
|
}
|
|
}
|