Simple Guide to Laravel Authorization with Gates
So basically, AUTHentication identifies a user, while AUTHorization determines what actions a given user can perform.
Out of the box Laravel provides two ways of authorizing actions: gates and policies. Policies are usually built around Models to determine if a user can perform one or more CRUD/BREAD actions on a particular Model. But, gates are usually more loose and can apply to any form of business action within the web application or service.
Gates are quite easy implement and i will prove that right now.
Designing Your Gates
Hypothetically, we may want to decide if a User can sit for a given exam.
We quickly move to our App\Providers
directory and open the AuthServiceProvider.php
file. within the AuthServiceProvider
class we define our gate in the boot
method like this:
use Illuminate\Support\Facades\Gate;
use App\Models\User;public function boot(){
$this->registerPolicies();
//You may now define your gates using the Gate Facade
// Gate::define('action-to-authorize', callback);
// callback should return boolean. Gate::define('sit-for-exam', function(User $user){
if($user->isStudent()){return true; } });}
Great! our gate has been defined. Note that your gates callback function should receive a User $user
followed by any other instance required for the Gate’s logic.
Instead of passing an anonymous function, You can also use a callback array to refer to a method in a particular class. Therefore, we can call the sitForExam()
method in the ExamPolicy
class like this:
use App\Policies\ExamPolicy;
...
//Inside the boot() method of AuthServiceProvider Gate::define('sit-for-exam', [ExamPolicy::class, 'sitForExam']);
Yeah, true… just like you do when defining routes. And thats how to define your gates, so simple and clean.
Mounting the Gates
After defining our gates, we can now mount them wherever we want like club bouncers within our Controller actions and blade templates.
class ExamController{
public function show(){
//if the gate does not allow user
//the user is sent away if(!Gate::allows('sit-for-exam')){
abort(403);
}
// others are free to sit for exam }}ORclass ExamController{
public function show(){
//Authorization Exception 403 for unauthorized users.
$this->authorize('sit-for-exam'); }}
For blade templates:
@can('sit-for-exam')
<!-- show exam components -->@else
<!-- oops you can sit for exam, Sorry -->@endcan
Authorization, as we can see is quite simple. you don’t need to start implementing your own authorization logic when you have it built-in.
Start mounting your gates…
I will appreciate feedback and corrections, even contributions to help Laravel developers that are new to this feature and the concepts entirely.
Thanks.