Laravel 7.x Authorization using Gates

In addition to providing authentication services out of the box, Laravel also provides a simple way to authorize user actions against a given resource. Like authentication, Laravel's approach to authorization is simple, and there are two primary ways of authorizing actions: gates and policies.

In this tutorial, i would like to explain you step by step gate and policy in laravel 7. we will create simple user role access control using laravel 7 gates and policies. i will give you very simple example of laravel 7 gates example.

If you want to create roles and permission with laravel then you can also follow this tutorial, i explained step by step: Laravel User Roles and Permissions Tutorial.

You need to just follow few step to lean how you can implement laravel 7 gate and policy with our project.

laravel-6-gate-and-policy-example

So let's start how to implement & setup roles and permissions in Laravel using gate.

Step 1 : Download Laravel Project

Open up your terminal and create a new Laravel project by typing in the following command

composer create-project --prefer-dist laravel/laravel blog

 

Step 2:  Make Auth

If you are using laravel version 6 then run below command to make auth

composer require laravel/ui --dev
php artisan ui vue --auth
npm install
npm run watch

If you are using below laravel version 6 then run below command to make auth

php artisan make:auth

 

Step 3 : Create Migration

In this step, we will create new migration for adding new column for "role". we will take enum datatype for role column. we will take only "admin", "manager" and "author" value on that. we will keep "editor" as default value.

so let's create as like bellow:

php artisan make:migration add_role_column_to_users_table

 

After this command you will find one file in following path "database/migrations" and you have to put bellow code in your migration file for create products table.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddRoleColumnToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->enum('role',  ['admin', 'author', 'editor'])->default('admin');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            //
        });
    }
}

 

Now you have to run this migration by following command:

php artisan migrate

 

Step 4: Add Some Dummy Users

You need to add some dummy users to users table as like bellow screen shot: So go to users table and insert some data or register.

laravel-gate-example

 

Step 6: Define Gates

In this step, we will define custom gate for user role access. we will define "admin", "author" and "editor" user. So let's update AuthServiceProvider.php file as like bellow:

app/Providers/AuthServiceProvider.php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        // 'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

         // define a admin user role 
         Gate::define('isAdmin', function($user) {
            return $user->role == 'admin';
         });
        
         //define a author user role 
         Gate::define('isAuthor', function($user) {
             return $user->role == 'author';
         });
       
         // define a editor role 
         Gate::define('isEditor', function($user) {
             return $user->role == 'editor';
         });
    }
}

 

Step 7:  Usages of Gates

Now, we will user our custom gate in our blade file. i created three button for each roles. When user will login then user will see only user button and same way others.So, let's update your home file as like bellow:

resources/views/home.blade.php

 

You can login with each user and output will be as like bellow:

Login as Admin

laravel-6-gate

Step 8 : Gates in Controller:

You can also use our custom gate in Controller file as like bellow:

use Illuminate\Auth\Access\Response;
use Illuminate\Support\Facades\Gate;

Route::get('hello',function(){
   
   return Gate::allows('isAdmin') ? Response::allow()
    : Response::deny('You do not edit this post.');

  //Or use
  
    if (Gate::allows('isAdmin')) {

        dd('Only admin can access this page');

    } else {

        dd('You are not Admin');

    }

   //Or use

    if (Gate::denies('isAdmin')) {

        dd('You are not admin');

    } else {

        dd('Only admin can access this page');

    }
 

});

 

After accessing as admin, you will see the below output

laravel-authorization-using-gate

After accessing as author, you will see the below output

laravel-gate-and-policy-example

Step 9 : Gate as Middleware

You can use role with middleware as like bellow:

Route::get('/items/delete', '[email protected]')->middleware('can:isAdmin')->name('items.delete');

Route::get('/items/update', '[email protected]')->middleware('can:isAuthor')->name('items.update');

Route::get('/items/create', '[email protected]')->middleware('can:isEditor')->name('items.create');

 

Read aslo : Laravel 6 Gate and Policy Example from Scratch

 

Just make sure that you don’t use gates and policies altogether for the same actions of the Model, otherwise it’ll create issues.I hope it can help you.