for the previous part we’ve set up user and group to continue I’ve implement Laravel Gate and show how package work
when you came across Laravel documentation and it’s will give two keyword
Gate and Policies
Gate is a class that perform all authorization cycle and Policie is a Class that organize a group of gate separate what your want
just a four step that you will learn from this chapter
first will control authorization for group and user
we create policies class with artisan
php artisan make:policy GroupPolicy --model=Group
php artisan make:policy UserPolicy --model=Group
that generates a class from a template
function in policy class use for check permission match in a controller
public function create(User $user) {
return in_array('group.create',$user->group->permission);
}
we use in_array to check the current action has in current login user permission
group.create come form Group Controller and create function and$user->group->permission an array containing a list of permission that we create in past chapter
in_array return boolean that easy for us
activate policy in function boot in AuthService provider
public function boot(){
$this->registerPolicies();
\Gate::resource('group','App\Policies\GroupPolicy');
\Gate::resource('group','App\Policies\UserPolicy');
}
we have many helper functions for check authorization like can, cant, allows and denieds,
for example check if user can’t edit group we throw 403 back
public function edit($id){
if(auth()->user()->cant('group.edit')){
return abort(403);
}
$group = \App\Group::find($id);
return view('group.edit',compact('group'));
}
now let’s try
you can use laravel debugbar view profile did you see Gate return success
I’ve try fail case
will remove user.create form admin role
add authorizartion check in policy
public function create(User $user){
return in_array('user.create',$user->group->permission);
}
and in controller
public function create() {
if(auth()->user()->cant('user.create')){
return abort(403);
}
$groups = Group::all();
return view('user.create',compact('groups'));
}
yep it’s work
so what should you do next
this is extra feature your can do when general business requirement done
your can repeat that process to cover all action