Laravel Gates and Policies Tutorial with Examples

In this tutorial, we will explore how to implement authentication and authorization using Laravel Gates and Policies. This will allow us to create a user role access control system that helps manage permissions within a Laravel application. [lwptoc]   Laravel Gates and Policies Overview Laravel Gates and Policies are essential components of Laravel’s Authorization system.…

By.

•

min read

In this tutorial, we will explore how to implement authentication and authorization using Laravel Gates and Policies. This will allow us to create a user role access control system that helps manage permissions within a Laravel application.

[lwptoc]

 

Laravel Gates and Policies Overview

Laravel Gates and Policies are essential components of Laravel’s Authorization system. They allow developers to define granular user access control within an application. This tutorial will demonstrate how to set up a Laravel project, create a migration table for user roles, and implement Gates and Policies to manage user access.

 

Setting Up a New Laravel Project

 

Installing Laravel

First, install a fresh Laravel application by running the following command in your terminal or command prompt:

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

 

Configuring Database

Next, configure the database connection in your .env file. Update the following values according to your database configuration:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

 

Creating a User Role Migration

To add a role column to the users table, create a new migration by running:

php artisan make:migration add_role_column_to_users_table

 

Update the newly created migration file in the database/migrations directory with the following code:

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

class AddRoleColumnToUsersTable extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->enum('role',  ['user', 'manager', 'admin'])->default('user');
        });
    }

    public function down()
    {
        // ...
    }
}

 

Now, run the migration using this command:

php artisan migrate

 

Adding Dummy Users

Add some dummy users to the users table. You can use Laravel Tinker to create these records.

 

Generating Authentication Scaffolding

To generate the authentication scaffolding, follow these steps:

Install the laravel/ui package:

composer require laravel/ui

Generate the authentication scaffolding:

php artisan ui bootstrap --auth

 

Install and run npm:

npm install
npm run dev

 

Defining Custom Gates

Update the AuthServiceProvider.php file in the app/Providers directory to define custom gates for user roles:

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

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [];

    public function boot()
    {
        $this->registerPolicies();

        // Define admin role
        Gate::define('isAdmin', function($user) {
           return $user->role == 'admin';
        });

        // Define manager role
        Gate::define('isManager', function($user) {
return $user->role == 'manager';
});
        // Define user role
        Gate::define('isUser', function($user) {
        return $user->role == 'user';
    });
  }
}

 

Implementing Gates in Blade Files

Update the home.blade.php file in the resources/views directory to use the custom gates for each role:

@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

 

Using Gates in Controllers

You can also use gates in controller files:

public function delete()
{
    if (Gate::allows('isAdmin')) {
        dd('Admin allowed');
    } else {
        dd('You are not Admin');
    }
}

public function delete()
{
    if (Gate::denies('isAdmin')) {
        dd('You are not admin');
    } else {
        dd('Admin allowed');
    }
}

public function delete()
{
    $this->authorize('isAdmin');
}

public function delete()
{
    $this->authorize('isUser');
}

 

Gates Middleware in Routes

To use gates as middleware in routes, update your routes/web.php file like this:

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');

 

Conclusion

By following this tutorial, you should now have a good understanding of how to implement Laravel Gates and Policies for user role access control. This will enable you to create a more secure and manageable Laravel application.

 

Some Common Questions:

 

What are Laravel Gates and Policies?

Laravel Gates and Policies are components of Laravel’s Authorization system that allow developers to define granular user access control within an application.

 

How do I define custom gates in Laravel?

Custom gates can be defined within the AuthServiceProvider.php file in the app/Providers directory using the Gate::define() method.

How can I use gates in Blade files?

Gates can be used in Blade files using the @can, @elsecan, and @endcan directives.

 

Can I use gates in controller files?

Yes, gates can be used in controller files using the Gate::allows(), Gate::denies(), and $this->authorize() methods.

 

How can I use gates as middleware in routes?

Gates can be used as middleware in routes by applying the can:middlewareNamemiddleware in your routes/web.php file.

 

Leave a Reply

Your email address will not be published. Required fields are marked *