<?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() {
Schema::table('users', function (Blueprint $table) {
//
});
}
}
By Hardik Savani January 18, 2020 Category : LaravelPauseUnmuteLoaded: 2.33%FullscreenToday's out topic is how to implement authentication using gate and policy in laravel application. we will learn laravel gate and policy with a user role access control system. i will show you how to define custom policy and how to use custom policy with gate in laravel application.
You can just follow this tutorial for Laravel Authorization Gates and Policies Example. you can also use this example in laravel 6, laravel 7, laravel 8 and laravel 9 application.
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 using gate and policy.
You need to just follow few step to lean how you can implement laravel gate and policy with our project.
Step 1: Install Laravel
first of all we need to get fresh Laravel version application using bellow command, So open your terminal OR command prompt and run bellow command:
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. So let's open .env file and fill all details like as bellow:
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:
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.
Now you have to run this migration by following command:
Step 4: Add Some Dummy Users
You need to add some dummy users to users table as like bellow screen shot:
You have to follow few step to make auth in your laravel application.
First you need to install laravel/ui package as like bellow:
Here, we need to generate auth scaffolding in laravel using laravel ui command. so, let's generate it by bellow command:
Now you need to run npm command, otherwise you can not see better layout of login and register page.
Install NPM:
Run NPM:
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
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
Now we can run our application.
Now you can test it by using following command:
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:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
\App\Models\User::factory(3)->create();
}
}
<?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';
});
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Gate;
class PostController extends Controller {
/**
* 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 update() {
if (Gate::allows('isManager')) {
dd('Manager allowed');
} else {
dd('You are not Admin');
}
}
/**
* Create a new controller instance.
*
* @return void
*/
public function create() {
if (Gate::allows('isUser')) {
dd('User allowed');
} else {
dd('You are not User');
}
}
}
@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
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\PostController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', [HomeController::class, 'index'])->name('home');
Route::get('/posts/delete', [PostController::class, 'delete'])->middleware('can:isAdmin')->name('post.delete');
Route::get('/posts/update', [PostController::class, 'update'])->middleware('can:isManager')->name('post.update');
Route::get('/posts/create', [PostController::class, 'create'])->middleware('can:isUser')->name('post.create');
composer create-project --prefer-dist laravel/laravel blog
DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=here your database name(blog)DB_USERNAME=here database username(root)DB_PASSWORD=here database password(root)
<?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() { }}
php artisan migrate
composer require laravel/ui
php artisan ui bootstrap --auth
npm install
npm run dev
<?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'; }); }}
@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
php artisan serve
/** * 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');}