Skip to content

Policies

Default controller using the Authorize middleware that's authorizes API requests using Laravel Authorization.

You can use make:policy Artisan command to generate a new policy class.

shell
php artisan make:policy UserPolicy --model=Entities\\User

Resource access

MethodRouteAbility
GET/viewAny
POST/create
GET/{resourceType}/view
PATCH/{resourceType}/update
DELETE/{resourceType}/delete

Authorized user must have access to ability depend on API request type.

For example if only authenticated user can view, update and delete itself, UserPolicy must be updated this way:

php
public function view(User $user, ResourceInterface $model): bool
{
    return $user === $model;
}

public function update(User $user, ResourceInterface $model): bool
{
    return $user === $model;
}

public function delete(User $user, ResourceInterface $model): bool
{
    return $user === $model;
}

Create and list resource not going to have 2nd parameter as we don't have specific entity object to be authorized.

Another example allows view any user (list action) and create users only to admin accounts.

php
public function viewAny(User $user): bool
{
    return $user->isAdmin();
}

public function create(User $user): bool
{
    return $user->isAdmin();
}

Use this table to understand which ability must be granted per each API action.

Relationships access

Relationship routes abilities generated by the action and relationship name appended to it.

To-One relationships

MethodRouteAbility
GET/{resourceType}/{id}/view
GET/{resourceType}/{id}/relationships/view
PATCH/{resourceType}/{id}/relationships/update

For example if we have "role" relationship in the user resource and only admin can change it and any other user can see it.

php
// Any one can see role
public function viewRole(User $user): bool
{
    return true;
}

// Only admin can update user role
public function updateRole(User $user): bool
{
    return $user->isAdmin();
}

To-Many relationships

MethodRouteAbility
GET/{resourceType}/{id}/viewAny
GET/{resourceType}/{id}/relationships/viewAny
PATCH/{resourceType}/{id}/relationships/update
POST/{resourceType}/{id}/relationships/attach
DELETE/{resourceType}/{id}/relationships/detach

In case multiple "roles" can be assigned to the user in your application, the policy definition going to look different.

php
// Anyone can see user roles
public function viewAnyRoles(User $user, ResourceInterface $resource): bool
{
    return true;
}

// Replace user roles
public function updateRoles(User $user, ResourceInterface $resource): bool
{
    return $user->isAdmin();
}

// Attach any new roles to resource
public function attachRoles(User $user, ResourceInterface $resource): bool
{
    return $user->isAdmin();
}

// Detach roles from resource
public function detachRoles(User $user, ResourceInterface $resource): bool
{
    return $user->isAdmin();
}