- Gates are closure
- Determine if a user is auth to perform a given action
- Gates always receive a user instance as first argument
- Gates allow us to define an auth rule using a simple closure based approach
- Gate is perfect place to implement the logic in closure when we want to authorize an action that is not related to any specific model
Gates Short Procedure
1. Define Gate boot() method of AuthServiceProvider.php
2. Use Gate in Resource view file using can()-elsecan()-else()
3. Gates in controller
a. Gate::allows(‘isXXX’) {};
b. Gate::denies(‘isXXX’) {};
c. $this->authorize(‘isXXX’);
4. Gates in Route Middleware
Route::get(‘post’,’PostController@delete’)
->middleware(‘can:isAdmin’)
->name(‘post.delete’);
————————————————–
===> Define Gate in boot() method of app\Providers\AuthServiceProvider.php
————————————————–
public function boot()
{
$this->registerPolicies();
-------------------------------------
// define a admin user role
-------------------------------------
Gate::define('isAdmin', function($user) {
return $user->role == 'admin';
});
-------------------------------------
// define a manager user role
-------------------------------------
Gate::define('isManager', function($user) {
return $user->role == 'manager';
});
-------------------------------------
// define a user role
-------------------------------------
Gate::define('isUser', function($user) {
return $user->role == 'user';
});
}
===> Resources display accordingly
————————————————–
@can('isAdmin')
<div class="btn btn-success btn-lg">
You have Admin Access
</div>
@elsecan('isManager')
<div class="btn btn-primary btn-lg">
You have Manager Access
</div>
@else
<div class="btn btn-info btn-lg">
You have User Access
</div>
@endcan
===> Gate Controller using Gate::allows(‘isXXX’)
——————————————————-
if (Gate::allows('isAdmin')) {
dd('Admin allowed');
} else {
dd('You are not Admin');
}
===> Gate Controller using Gate::denies(‘isXXX’)
——————————————————-
if (Gate::denies('isAdmin')) {
dd('You are not admin');
} else {
dd('Admin allowed');
}
===> Gate Controller using $this->authorize(‘isXXX’)
——————————————————-
$this->authorize('isAdmin');