Via The User model
The Laravel User model contains two methods that help with authorisations using Policies
; can
and can't
. These two can be used to determine if a user has authorisation or not on a model respectively.
To check if a user can view a content or not, you can do the following:
if($user->can('view', $content)){
/* user can view content */
}
OR
if($user->cant('view', $content)){
/* user cannot view content */
}
Via Middleware
Route::get('/contents/{id}, function(Content $content){
/* user can view content */
})->middleware('can:view,content');
Via Controllers
Laravel provides a helper method, called authorize
that takes the name of the policy and the associated model as arguments, and either authorizes the action based on your authorisation logic or denies the action and throws an AuthorizationException
which the Laravel Exception handler converts to a 403 HTTP response
.
pubic function show($id)
{
$content = Content::find($id);
$this->authorize('view', $content);
/* user can view content */
}