-
Notifications
You must be signed in to change notification settings - Fork 17
Checking Authority rules
After authority rules are defined, you can use the Authority::can()
method in the controller or view to check the user's permission for a given action and object.
Authority::can('destroy', $this->project);
The Authority::cannot()
method is for convenience and performs the opposite check of Authority::can()
Authority::cannot('destroy', $this->project);
Also see Authorizing Controller Actions and Custom Actions.
You can also pass the class name instead of an instance (if you don't have one handy).
@if (Authority::can('create', 'Project'))
{{ link_to_route('projects.create', "New Project") }}
@endif
@if (Authority::can('create', 'Project'))
{!! link_to_route('projects.create', "New Project") !!}
@endif
Important: If a conditional callback exist it will be ignored when checking on a class, and it will return true
. For example:
$authority->allow('read', 'Project', function ($self, $project) {
return $project->priority === 3;
});
Authority::can('read', 'Project'); // returns true
It is impossible to answer this can()
question completely because not enough detail is given. Here the class does not have a priority
property to check on.
Think of it as asking "can the current user read a project?". The user can read a project, so this returns true
. However it depends on which specific project you're talking about. If you are doing a class check, it is important you do another check once an instance becomes available so the conditional callback can be used.
The reason for this behavior is because of the controller index
action. Since the authorizeResource()
before filter has no instance to check on, it will use the Project
class. If the authorization failed at that point then it would be impossible to filter the results later when Fetching Records.
That is why passing a class name to can()
will return true
.