Laravel 6 Authorization using Gates and Policies

Laravel 6 Authorization using Gates and Policies

In this Laravel 6 Authorization tutorial, I would like to explain how to create a simple user role access control using Laravel 6 gates and policies. I will give you a very simple example of Laravel 6 gates. In this example i will show you how we can easily implement role access control in laravel 6 using gate and policy.

In this tutorial, i would like to explain you step by step gate and policy in Laravel 6. we will create simple user role access control using laravel 6 gates and policies. I will give you very simple example of Laravel 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.

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 3: Create Migration Table

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 "user", "manager" and "admin" value on that. we will keep "user" 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.

<?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 as like bellow screen shot:

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:

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

Advantages of Hiring PHP Developer for your Website Project

Advantages of Hiring PHP Developer for your Website Project

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is...

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is to learn the language yourself. That’s why PHP developers are there to make your life easy. This article will give us the advantages and requirements of Hire PHP Developer for our very own website project.

First of all, let us understand the value the right developer brings to the project and why it is important for your business.

A website is a major component of any company/business and is very important for its face value, the way it represents the company on the internet is critical for any business to succeed. This is the reason why companies are looking for PHP developers who can develop their webpage.

If you're planning to do an online business, your PHP programmer will be the first person to transfer your thinking onto the webpage. You should, therefore, employ developers from PHP to make your hypothetical idea a reality.

With this software programming language, PHP developers all-around can easily build website frameworks, web content management systems, web template systems, and various other web-based designs.

Some of the reasons why we need to outsource these developers are:

Not everyone is the best in each field, all of us have our specific skills and talents hence, PHP developers are also the best at what they do. The time and money spent on the training of the in house employees would be saved if the professional PHP developers are hired. Instead of multitasking, if the employees were to focus on what they’re good at it would increase productivity too.

The PHP developers would be much more professional than the in-house workers. It would lead to the seriousness of work. Hence, on-time delivery is guaranteed with hired PHP developers.

In addition to these benefits, you would also be able to track your project through every stage in constant communication with your online team. These advantages make it incredibly popular and smart to hire a PHP developer.

The PHP developers have in-depth knowledge of PHP, HTML and various frameworks in terms of technical capabilities. Hiring PHP developers are advised to give your website a professional look based on PHP.

Much of web success depends on the involvement of social media. The developer can add to your social networking pages a feature that explicitly redirects visitors. In addition, SEO experts also suggest better connections to the website's social network.

Just like a tailor stitches our dresses according to our preferences and is ready to make last-minute changes. A PHP developer will also be available at the nick of your call to make the website just the way you want it to be and have a customized solution for every problem.

Read also: Why & How to Hire Dedicated PHP Developer

At some point in your business, you’re going to have problems regarding your webpage due to the rapidly changing technology, instead of struggling with ideas like these and not being able to come up with an appropriate solution a PHP web developer could help us with our problems just like any technician would help us with the problems we face in our offices or any architect would help us with designing the structure of a building or any interior designer would help us with setting up our home. The PHP development company are hubs of workers who would help us overcome these problems and are always there.

Source by

Hire PHP Developer and Web Developer for your Online Business

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]

Top Laravel Development Companies Reviews

Top Laravel Development Companies Reviews

Among the list of Best Laravel development companies, TopDevelopers has chosen the most acclaimed laravel developers for the visitors so as to make them avail the extremely wonderful service ever offered. The web development companies listed here...

Among the list of Best Laravel development companies, TopDevelopers has chosen the most acclaimed laravel developers for the visitors so as to make them avail the extremely wonderful service ever offered. The web development companies listed here have passed the stringent assessments carried out by TopDevelopers in order to get approved as top Laravel service providers. Get in touch with the most sought-after Laravel developers in the market for your assistance.

Here is the List of Best Laravel Development Companies.