-
app/Scopes/UserAccessScope.php
Open in GitHubuse App\Exceptions\Entities\AuthorizationException; use App\Enums\Role; use Illuminate\Contracts\Database\Query\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Scope; use Throwable; class UserAccessScope implements Scope { public function apply(Builder $builder, Model $model): ?Builder { if (!auth()->hasUser()) { return null; } if (app()->runningInConsole()) { return $builder; } $user = optional(request())->user(); throw_unless($user, new AuthorizationException); if ($user->hasRole([Role::ADMIN, Role::MANAGER, Role::AUDITOR])) { return $builder; } return $builder ->where('id', $user->id) ->orWhereHas('projectsRelation', static fn(Builder $builder) => $builder ->whereIn('project_id', static fn(Builder $builder) => $builder ->from('projects_users') ->select('project_id') ->where(static fn(Builder $builder) => $builder ->where('user_id', $user->id) ->where('role_id', Role::MANAGER->value)) ->orWhere(static fn(Builder $builder) => $builder ->where('user_id', $user->id) ->where('role_id', Role::AUDITOR->value)))); } }
-
app/Models/User.php
Open in GitHubuse App\Scopes\UserAccessScope; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { // ... protected static function boot(): void { parent::boot(); static::addGlobalScope(new UserAccessScope); } // ... }
-
tests/Feature/Users/ListTest.php
Open in GitHubuse Tests\TestCase; use App\Models\User; class ListTest extends TestCase { // ... public function test_list_as_project_manager_with_global_scope(): void { $response = $this->actingAs($this->projectManager)->postJson(self::URI, ['global_scope' => true]); $users = User::withoutGlobalScope(\App\Scopes\UserAccessScope::class) ->setEagerLoads([]) ->get() ->toArray(); $response->assertOk(); $response->assertExactJson($users); } // ... }