PHP code example of langsys / laravel-access-guard
1. Go to this page and download the library: Download langsys/laravel-access-guard library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
langsys / laravel-access-guard example snippets
use Langsys\AccessGuard\Facades\AccessGuard;
AccessGuard::authorize('edit_projects', $project); // throws AuthorizationException if denied
if (AccessGuard::allows('view_projects', $project)) { /* ... */ }
// Keep only the entities the current subject may see:
$visible = AccessGuard::filterByPermission('view_projects', $projects);
use Langsys\AccessGuard\Contracts\Authorizable;
use Langsys\AccessGuard\Contracts\AuthorizableByUser;
class User extends Authenticatable implements Authorizable, AuthorizableByUser
{
public function isSuperAdmin(): bool
{
return $this->type === UserType::SuperAdmin;
}
public function userRoleInEntity(mixed $entity): ?object
{
return $this->roleInEntity($entity); // your pivot lookup → a Role
}
public function roleHasPermission(object $role, string $permission): bool
{
return $role->hasPermission($permission);
}
public function userHasDisabledEntity(mixed $entity): bool
{
return $this->disabledEntities()->whereKey($entity->getKey())->exists();
}
}
use Langsys\AccessGuard\Contracts\GuardableResource;
class Project extends Model implements GuardableResource {}
use Langsys\AccessGuard\Concerns\AuthorizesWithApiKeys;
use Langsys\AccessGuard\Contracts\GuardableResource;
class Project extends Model implements GuardableResource
{
use AuthorizesWithApiKeys;
}
$project->grantApiKey($apiKey); // this key may now act on this project
$project->revokeApiKey($apiKey);
use Langsys\AccessGuard\Concerns\HasRolesInEntities;
use Langsys\AccessGuard\Contracts\AuthorizableInEntity;
class User extends Authenticatable implements Authorizable, AuthorizableInEntity
{
use HasRolesInEntities;
}
$user->assignRole('project_admin', $project); // role value, backed enum, or Role model
$user->syncRoles(['viewer'], $project);
$user->removeRole('project_admin', $project);
$user->hasRole('project_admin', $project); // bool
$user->hasPermissionInEntity('edit_projects', $project); // unions every role in the entity
$user->rolesInEntity($project); // Collection<Role>
$user->permissionsInEntity($project); // array<string>
$user->can('edit_projects', $project);
$this->authorize('edit_projects', $project); // in a controller
// @can('edit_projects', $project) ... @endcan