How to use Laravel 7/6 Authorization using Gates?

Admin   Laravel   46  2020-08-12 08:20:02

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

Authorization is primary requirement of each project. we almost need to implementation of auth and user access by role wise. in this example i will show you how we can easily implement role access control in laravel 6 using gate and policy.

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 6 gate and policy with our project.

Step 1: Install Laravel 6

first of all we need to get fresh Laravel 6 version application using bellow command, So open your terminal OR command prompt and run bellow command:

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

Step 2: Database Configuration

In second step, we will make database configuration for example database name, username, password etc for our crud application of laravel 6. So let's open .env file and fill all details like as bellow:

.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 5: Generate Auth Scaffold

You have to follow few step to make auth in your laravel 6 application.

First you need to install laravel/ui package as like bellow:

composer require laravel/ui

Here, we need to generate auth scaffolding in laravel 6 using laravel ui command. so, let's generate it by bellow command:

php artisan ui bootstrap --auth

Now you need to run npm command, otherwise you can not see better layout of login and register page.

Install NPM:

npm install

Run NPM:

npm run dev

Step 6: Define Custom Gates

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

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

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

@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

Now we can run our application.

Now you can test it by using following command:

php artisan serve

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

User Login

Manager Login

Admin Login

Gates in Controller:

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:

You can use role with middleware as like bellow:

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

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

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

I hope it can help you...