In this tutorial, we will learn How to use Laravel 8/7 Authorization using Gates


Here, you will know step by step gate and policy in laravel 8/7. we will create simple user role access control using laravel 7/6 gates and policies. We will give you a very simple example of laravel 8/7 gates.


Step 1: 

Install Laravel 6

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


Step 2: 

Database Configuration 

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)



Step 3: 

Create Migration Table

php artisan make:migration add_role_column_to_users_table


<?php
  
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',  ['user', 'manager', 'admin'])->default('user');
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
           
    }
}


 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


Step 5: 

Generate Auth Scaffold

composer require laravel/ui
php artisan ui bootstrap --auth

Install NPM:

npm install

Run NPM:

npm run dev

Step 6: 

Define Custom Gates app/Providers/AuthServiceProvider.php

<?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 = [
            
    ];
  
    /**
     * 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 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';
        });
    }
}

Step 7: 

Use Gates resources/views/home.blade.php

@extends('layouts.app')
  
@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Dashboard</div>
   
                <div class="card-body">
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif
  
                    @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
  
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

 test it by using following command:

php artisan serve


You can also check in Controller file as like bellow:


/**

 * Create a new controller instance.

 *

 * @return void

 */

public function delete()

{

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

        dd('Admin allowed');

    } else {

        dd('You are not Admin');

    }

}


/**

 * Create a new controller instance.

 *

 * @return void

 */

public function delete()

{

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

        dd('You are not admin');

    } else {

        dd('Admin allowed');

    }

}

/**

 * Create a new controller instance.

 *

 * @return void

 */

public function delete()

{

    $this->authorize('isAdmin');

}

/**

 * Create a new controller instance.

 *

 * @return void

 */

public function delete()

{

    $this->authorize('isUser');

}


Gates in Route with Middleware:

Route::get('/posts/delete', 'PostController@delete')->middleware('can:isAdmin')->name('post.delete');
Route::get('/posts/update', 'PostController@update')->middleware('can:isManager')->name('post.update');
Route::get('/posts/create', 'PostController@create')->middleware('can:isUser')->name('post.create');

May this example help you.