Laravel 5.4 User Role and Permissions (ACL) with Spatie Laravel-Permission Middlware
In this post we will give you information about Laravel 5.4 User Role and Permissions (ACL) with Spatie Laravel-Permission Middlware. Hear we will give you detail about Laravel 5.4 User Role and Permissions (ACL) with Spatie Laravel-Permission MiddlwareAnd how to use it also give you demo for it if it is necessary.
In this Laravel tutorial, I will tell you how to implement role and permission (ACL) to a user in the Laravel application.
For example, A user may have permission to change anything but other user may have permission to read only within the application.
In this example, I will create a simple blog application with role and permission that means you can give access to user to edit post, create post, delete post etc.
I will define role and permission on database level that will manage by a UI in the admin panel.
There are so many package built in Laravel to implement role and permission but for this example I am going to use spatie/laravel-permission
package.
By the end of this tutorial, you will be able to define rights for authenticated users using role and permissions.
Install Laravel 5.5 and Configure the permission package
First, We will install fresh Laravel application by running following composer command :
composer create-project --prefer-dist laravel/laravel blog
After successfully installation, create the database and update database credential in .env
file.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=blog DB_USERNAME=root DB_PASSWORD=
Now install the Laravel permission package :
composer require spatie/laravel-permission
Now add the provider in the list of service provider, Open config/app.php
file and add SpatiePermissionPermissionServiceProvider::class.
'providers' => [ ... SpatiePermissionPermissionServiceProvider::class, ];
Now run the artisan command to publish migration file :
php artisan vendor:publish --provider="SpatiePermissionPermissionServiceProvider" --tag="migrations"
To create table from migration file, run following artisan command :
php artisan migrate
If you are running lower version of MySQL then you may get following error :
[IlluminateDatabaseQueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table users add unique users_email_unique(email)) [PDOException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
To avoid this error, edit the appProvidersAppServiceProvider.php
file :
use IlluminateSupportFacadesSchema; public function boot() { Schema::defaultStringLength(191); }
Now you can run migrate command again to create table into database.
Laravel Collective HTML Form builder
Now install the Laravel Collective HTML Form builder to avoid the error “Class Form not found”.
And then add provider to providers array
'providers' => [ ... CollectiveHtmlHtmlServiceProvider::class, ];
Next add the aliases to aliases array :
'aliases' => [ ... 'Form' => CollectiveHtmlFormFacade::class, 'Html' => CollectiveHtmlHtmlFacade::class, ],
With the fresh installation of Laravel, You will have User
model by default.
Now I need to create Role, Permission and Post models with their resource controller.
SpatiePermission already have role and permissions model, you just need to publish them but I will create manually Model and Controller class by running following command :
// Create Role model and resource controller php artisan make:model Role -c --resource // Create Permission model and resource controller php artisan make:model Permission -c --resource // Create Post model with migration and resource controller php artisan make:model Post -m -c --resource
By default Role and Permission class will extend default Model
class :
- class Role extends Model {}
class Role extends Model { }
You need to edit Role and Permission class to extend SpatiePermissionModels
.
- // Permission Model
- class Permission extendsSpatiePermissionModelsPermission {}
- // Role Model
- class Role extendsSpatiePermissionModelsRole {}
// Permission Model class Permission extends SpatiePermissionModelsPermission { } // Role Model class Role extends SpatiePermissionModelsRole { }
When you run php artisan make:model Post -m -c --resource
command then you will have migration file to create post table, So edit you migration file :
2017_09_02_052113_create_posts_table.php
- Schema::create('posts',function(Blueprint $table){
- $table->increments('id');
- $table->string('title');
- $table->text('body');
- $table->timestamps();
- });
Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('body'); $table->timestamps(); });
Run migrate command to create post table again.
Next we need to add HasRoles
trait to User model.
- use SpatiePermissionTraitsHasRoles;
- class User extends Authenticatable {
- use HasRoles;
- ...
- }
use SpatiePermissionTraitsHasRoles; class User extends Authenticatable { use HasRoles; ... }
Default Permission
Next we will add some default permission in Permission Model :
- <?php
- namespace App;
- use IlluminateDatabaseEloquentModel;
- class Permission extendsSpatiePermissionModelsPermission
- {
- public staticfunctiondefaultPermissions()
- {
- return[
- 'viewPost',
- 'addPost',
- 'editPost',
- 'deletePost',
- ];
- }
- }
<?php namespace App; use IlluminateDatabaseEloquentModel; class Permission extends SpatiePermissionModelsPermission { public static function defaultPermissions() { return [ 'viewPost', 'addPost', 'editPost', 'deletePost', ]; } }
Now we will use Database seeder to seed data for testing our app.
database/seeds/DatabaseSeeder.php
- <?php
- use IlluminateDatabaseSeeder;
- use AppPermission;
- use AppRole;
- use AppUser;
- use AppPost;
- class DatabaseSeeder extends Seeder
- {
- /**
- * Run the database seeds.
- *
- * @return void
- */
- public functionrun()
- {
- // Ask for confirmation to refresh migration
- if($this->command->confirm('Do you wish to refresh migration before seeding, Make sure it will clear all old data ?')){
- $this->command->call('migrate:refresh');
- $this->command->warn("Data deleted, starting from fresh database.");
- }
- // Seed the default permissions
- $permissions= Permission::defaultPermissions();
- foreach($permissionsas$permission){
- Permission::firstOrCreate(['name'=>$permission]);
- }
- $this->command->info('Default Permissions added.');
- // Ask to confirm to assign admin or user role
- if($this->command->confirm('Create Roles for user, default is admin and user? [y|N]', true)){
- // Ask for roles from input
- $roles=$this->command->ask('Enter roles in comma separate format.','Admin,User');
- // Explode roles
- $rolesArray=explode(',',$roles);
- // add roles
- foreach($rolesArrayas$role){
- $role= Role::firstOrCreate(['name'=>trim($role)]);
- if($role->name =='Admin'){
- // assign all permissions to admin role
- $role->permissions()->sync(Permission::all());
- $this->command->info('Admin will have full rights');
- }else{
- // for others, give access to view only
- $role->permissions()->sync(Permission::where('name','LIKE','view_%')->get());
- }
- // create one user for each role
- $this->createUser($role);
- }
- $this->command->info('Roles '.$roles.' added successfully');
- }else{
- Role::firstOrCreate(['name'=>'User']);
- $this->command->info('By default, User role added.');
- }
- }
- /**
- * Create a user with given role
- *
- * @param $role
- */
- private functioncreateUser($role)
- {
- $user=factory(User::class)->create();
- $user->assignRole($role->name);
- if($role->name =='Admin'){
- $this->command->info('Admin login details:');
- $this->command->warn('Username : '.$user->email);
- $this->command->warn('Password : "secret"');
- }
- }
- }
<?php use IlluminateDatabaseSeeder; use AppPermission; use AppRole; use AppUser; use AppPost; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // Ask for confirmation to refresh migration if ($this->command->confirm('Do you wish to refresh migration before seeding, Make sure it will clear all old data ?')) { $this->command->call('migrate:refresh'); $this->command->warn("Data deleted, starting from fresh database."); } // Seed the default permissions $permissions = Permission::defaultPermissions(); foreach ($permissions as $permission) { Permission::firstOrCreate(['name' => $permission]); } $this->command->info('Default Permissions added.'); // Ask to confirm to assign admin or user role if ($this->command->confirm('Create Roles for user, default is admin and user? [y|N]', true)) { // Ask for roles from input $roles = $this->command->ask('Enter roles in comma separate format.', 'Admin,User'); // Explode roles $rolesArray = explode(',', $roles); // add roles foreach($rolesArray as $role) { $role = Role::firstOrCreate(['name' => trim($role)]); if( $role->name == 'Admin' ) { // assign all permissions to admin role $role->permissions()->sync(Permission::all()); $this->command->info('Admin will have full rights'); } else { // for others, give access to view only $role->permissions()->sync(Permission::where('name', 'LIKE', 'view_%')->get()); } // create one user for each role $this->createUser($role); } $this->command->info('Roles ' . $roles . ' added successfully'); } else { Role::firstOrCreate(['name' => 'User']); $this->command->info('By default, User role added.'); } } /** * Create a user with given role * * @param $role */ private function createUser($role) { $user = factory(User::class)->create(); $user->assignRole($role->name); if( $role->name == 'Admin' ) { $this->command->info('Admin login details:'); $this->command->warn('Username : '.$user->email); $this->command->warn('Password : "secret"'); } } }
Next run the seeder using following command :
php artisan db:seed
Ok, Everything is setup now.
Next we will perform simple CRUD operation on “Role”, “Permission”, “User” and “Post” module.
Register routes
Now add following routes in your routes/web.php
:
Route::group( ['middleware' => ['auth']], function() { Route::resource('users', 'UserController'); Route::resource('roles', 'RoleController'); Route::resource('posts', 'PostController'); Route::resource('permissions','PermissionController'); });
Master Layout ‘resources/views/layouts/app.blade.php’
- <!DOCTYPEhtml>
- <htmllang="{{ app()->getLocale() }}">
- <head>
- <metacharset="utf-8">
- <metahttp-equiv="X-UA-Compatible"content="IE=edge">
- <metaname="viewport"content="width=device-width, initial-scale=1">
- <!-- CSRF Token -->
- <metaname="csrf-token"content="{{ csrf_token() }}">
- <title>{{ config('app.name', 'Laravel') }}</title>
- <!-- Styles -->
- <linkhref="{{ asset('css/app.css') }}"rel="stylesheet">
- </head>
- <body>
- <divid="app">
- <navclass="navbar navbar-default navbar-static-top">
- <divclass="container">
- <divclass="navbar-header">
- <!-- Collapsed Hamburger -->
- <buttontype="button"class="navbar-toggle collapsed"data-toggle="collapse"data-target="#app-navbar-collapse">
- <spanclass="sr-only">Toggle Navigation</span>
- <spanclass="icon-bar"></span>
- <spanclass="icon-bar"></span>
- <spanclass="icon-bar"></span>
- </button>
- <!-- Branding Image -->
- <aclass="navbar-brand"href="{{ url('/') }}">
- {{ config('app.name', 'Laravel') }}
- </a>
- </div>
- <divclass="collapse navbar-collapse"id="app-navbar-collapse">
- <!-- Left Side Of Navbar -->
- <ulclass="nav navbar-nav">
-
- </ul>
- <!-- Right Side Of Navbar -->
- <ulclass="nav navbar-nav navbar-right">
- <!-- Authentication Links -->
- @if (Auth::guest())
- <li><ahref="{{ route('login') }}">Login</a></li>
- <li><ahref="{{ route('register') }}">Register</a></li>
- @else
- <liclass="dropdown">
- <ahref="#"class="dropdown-toggle"data-toggle="dropdown"role="button"aria-expanded="false">
- {{ Auth::user()->name }} <spanclass="caret"></span>
- </a>
- <ulclass="dropdown-menu"role="menu">
- <li>
- <ahref="{{ route('logout') }}"
- onclick="event.preventDefault();
- document.getElementById('logout-form').submit();">
- Logout
- </a>
- <formid="logout-form"action="{{ route('logout') }}"method="POST"style="display: none;">
- {{ csrf_field() }}
- </form>
- </li>
- </ul>
- </li>
- @endif
- </ul>
- </div>
- </div>
- </nav>
- @if ($message = Session::get('success'))
- <divclass="alert alert-success">
- <p>{{ $message }}</p>
- </div>
- @endif
- @yield('content')
- </div>
- <!-- Scripts -->
- <scriptsrc="{{ asset('js/app.js') }}"></script>
- </body>
- </html>
<!DOCTYPE html> <html lang="{{ app()->getLocale() }}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>{{ config('app.name', 'Laravel') }}</title> <!-- Styles --> <link href="{{ asset('css/app.css') }}" rel="stylesheet"> </head> <body> <div id="app"> <nav > <div > <div > <!-- Collapsed Hamburger --> <button type="button" data-toggle="collapse" data-target="#app-navbar-collapse"> <span >Toggle Navigation</span> <span ></span> <span ></span> <span ></span> </button> <!-- Branding Image --> <a href="{{ url('/') }}"> {{ config('app.name', 'Laravel') }} </a> </div> <div id="app-navbar-collapse"> <!-- Left Side Of Navbar --> <ul > </ul> <!-- Right Side Of Navbar --> <ul > <!-- Authentication Links --> @if (Auth::guest()) <li><a href="{{ route('login') }}">Login</a></li> <li><a href="{{ route('register') }}">Register</a></li> @else <li > <a href="#" data-toggle="dropdown" role="button" aria-expanded="false"> {{ Auth::user()->name }} <span ></span> </a> <ul role="menu"> <li> <a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> Logout </a> <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;"> {{ csrf_field() }} </form> </li> </ul> </li> @endif </ul> </div> </div> </nav> @if ($message = Session::get('success')) <div > <p>{{ $message }}</p> </div> @endif @yield('content') </div> <!-- Scripts --> <script src="{{ asset('js/app.js') }}"></script> </body> </html>
User Management Module
Now add following code in UserController.php
:
- <?php
- namespace AppHttpControllers;
- use IlluminateHttpRequest;
- use AppUser;
- use AppRole;
- use AppPermission;
- class UserController extends Controller
- {
- /**
- * Create a new controller instance.
- *
- * @return void
- */
- public function__construct()
- {
- $this->middleware('auth');
- }
- /**
- * Show the application dashboard.
- *
- * @return IlluminateHttpResponse
- */
- public functionindex()
- {
- $users= User::latest()->paginate();
- returnview('users.index',compact('users'));
- }
- public functioncreate()
- {
- $roles= Role::get();
- returnview('users.create',compact('roles'));
- }
- public functionstore(Request $request)
- {
- $this->validate($request,[
- 'name'=>'required',
- 'email'=>'required|email|unique:users',
- 'password'=>'required|min:6|confirmed',
- 'roles'=>'required'
- ]);
- $user= User::create($request->except('roles'));
- if($request->roles <>''){
- $user->roles()->attach($request->roles);
- }
- returnredirect()->route('users.index')->with('success','User has been created');
- }
- public functionedit($id){
- $user= User::findOrFail($id);
- $roles= Role::get();
- returnview('users.edit',compact('user','roles'));
- }
- public functionupdate(Request $request,$id){
- $user= User::findOrFail($id);
- $this->validate($request,[
- 'name'=>'required|max:120',
- 'email'=>'required|email|unique:users,email,'.$id,
- 'password'=>'required|min:6|confirmed'
- ]);
- $input=$request->except('roles');
- $user->fill($input)->save();
- if($request->roles <>''){
- $user->roles()->sync($request->roles);
- }
- else{
- $user->roles()->detach();
- }
- returnredirect()->route('users.index')->with('success',
- 'User successfully updated.');
- }
- public functiondestroy($id){
- $user= User::findOrFail($id);
- $user->delete();
- returnredirect()->route('users.index')->with('success',
- 'User successfully deleted.');
- }
- }
<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppUser; use AppRole; use AppPermission; class UserController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return IlluminateHttpResponse */ public function index() { $users = User::latest()->paginate(); return view('users.index', compact('users')); } public function create() { $roles = Role::get(); return view('users.create', compact('roles')); } public function store(Request $request) { $this->validate($request, [ 'name' => 'required', 'email' => 'required|email|unique:users', 'password' => 'required|min:6|confirmed', 'roles' => 'required' ]); $user = User::create($request->except('roles')); if($request->roles <> ''){ $user->roles()->attach($request->roles); } return redirect()->route('users.index')->with('success','User has been created'); } public function edit($id) { $user = User::findOrFail($id); $roles = Role::get(); return view('users.edit', compact('user', 'roles')); } public function update(Request $request, $id) { $user = User::findOrFail($id); $this->validate($request, [ 'name'=>'required|max:120', 'email'=>'required|email|unique:users,email,'.$id, 'password'=>'required|min:6|confirmed' ]); $input = $request->except('roles'); $user->fill($input)->save(); if ($request->roles <> '') { $user->roles()->sync($request->roles); } else { $user->roles()->detach(); } return redirect()->route('users.index')->with('success', 'User successfully updated.'); } public function destroy($id) { $user = User::findOrFail($id); $user->delete(); return redirect()->route('users.index')->with('success', 'User successfully deleted.'); } }
In store()
method, A new user is registered with selected roles.
In update()
method, I will update the user details and update roles with sync
method.
Use mutator in appUser.php
file that will encrypt password while registering new user.
appUser.php
- public functionsetPasswordAttribute($password)
- {
- $this->attributes['password']=bcrypt($password);
- }
public function setPasswordAttribute($password) { $this->attributes['password'] = bcrypt($password); }
User Views
There are three views required :
index.blade.php
This file will contain a HTML Table with list of all users.
- {{-- resourcesviewsusersindex.blade.php --}}
- @extends('layouts.app')
- @section('title', '| Users')
- @section('content')
- <divclass="col-lg-10 col-lg-offset-1">
- <h1><iclass="fa fa-users"></i> User Management
- <ahref="{{ route('roles.index') }}"class="btn btn-default pull-right">Roles</a>
- <ahref="{{ route('permissions.index') }}"class="btn btn-default pull-right">Permissions</a>
- <ahref="{{ route('users.create') }}"class="btn btn-success">Add User</a>
- </h1>
- <hr>
- <divclass="table-responsive">
- <tableclass="table table-bordered table-striped">
- <thead>
- <tr>
- <th>Name</th>
- <th>Email</th>
- <th>Date/Time Added</th>
- <th>User Roles</th>
- <th>Action</th>
- </tr>
- </thead>
- <tbody>
- @foreach ($users as $user)
- <tr>
- <td>{{ $user->name }}</td>
- <td>{{ $user->email }}</td>
- <td>{{ $user->created_at->format('F d, Y h:ia') }}</td>
- <td>{{ $user->roles()->pluck('name')->implode(' ') }}</td>
- <td>
- <ahref="{{ route('users.edit', $user->id) }}"class="btn btn-warning">Edit</a>
- {!! Form::open(['method' => 'DELETE', 'route' => ['users.destroy', $user->id] ]) !!}
- {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
- {!! Form::close() !!}
- </td>
- </tr>
- @endforeach
- </tbody>
- </table>
- </div>
- </div>
- @endsection
{{-- resourcesviewsusersindex.blade.php --}} @extends('layouts.app') @section('title', '| Users') @section('content') <div > <h1><i ></i> User Management <a href="{{ route('roles.index') }}" >Roles</a> <a href="{{ route('permissions.index') }}" >Permissions</a> <a href="{{ route('users.create') }}" >Add User</a> </h1> <hr> <div > <table > <thead> <tr> <th>Name</th> <th>Email</th> <th>Date/Time Added</th> <th>User Roles</th> <th>Action</th> </tr> </thead> <tbody> @foreach ($users as $user) <tr> <td>{{ $user->name }}</td> <td>{{ $user->email }}</td> <td>{{ $user->created_at->format('F d, Y h:ia') }}</td> <td>{{ $user->roles()->pluck('name')->implode(' ') }}</td> <td> <a href="{{ route('users.edit', $user->id) }}" >Edit</a> {!! Form::open(['method' => 'DELETE', 'route' => ['users.destroy', $user->id] ]) !!} {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} </td> </tr> @endforeach </tbody> </table> </div> </div> @endsection
create.blade.php
- {{-- resourcesviewsuserscreate.blade.php --}}
- @extends('layouts.app')
- @section('title', '| Create User')
- @section('content')
- <divclass='col-lg-4col-lg-offset-4'>
- <h1><iclass='fafa-user-plus'></i> Create User</h1>
- <hr>
- {!! Form::open(array('url' => 'users')) !!}
- <divclass="form-group @if ($errors->has('name')) has-error @endif">
- {!! Form::label('name', 'Name') !!}
- {!! Form::text('name', '', array('class' => 'form-control')) !!}
- </div>
- <divclass="form-group @if ($errors->has('email')) has-error @endif">
- {!! Form::label('email', 'Email') !!}
- {!! Form::email('email', '', array('class' => 'form-control')) !!}
- </div>
- <divclass="form-group @if ($errors->has('roles')) has-error @endif">
- @foreach ($roles as $role)
- {!! Form::checkbox('roles[]', $role->id ) !!}
- {!! Form::label($role->name, ucfirst($role->name)) !!}<br>
- @endforeach
- </div>
- <divclass="form-group @if ($errors->has('password')) has-error @endif">
- {!! Form::label('password', 'Password') !!}<br>
- {!! Form::password('password', array('class' => 'form-control')) !!}
- </div>
- <divclass="form-group @if ($errors->has('password')) has-error @endif">
- {!! Form::label('password', 'Confirm Password') !!}<br>
- {!! Form::password('password_confirmation', array('class' => 'form-control')) !!}
- </div>
- {!! Form::submit('Register', array('class' => 'btn btn-primary')) !!}
- {!! Form::close() !!}
- </div>
- @endsection
{{-- resourcesviewsuserscreate.blade.php --}} @extends('layouts.app') @section('title', '| Create User') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-user-plus'></i> Create User</h1> <hr> {!! Form::open(array('url' => 'users')) !!} <div > {!! Form::label('name', 'Name') !!} {!! Form::text('name', '', array('class' => 'form-control')) !!} </div> <div > {!! Form::label('email', 'Email') !!} {!! Form::email('email', '', array('class' => 'form-control')) !!} </div> <div > @foreach ($roles as $role) {!! Form::checkbox('roles[]', $role->id ) !!} {!! Form::label($role->name, ucfirst($role->name)) !!}<br> @endforeach </div> <div > {!! Form::label('password', 'Password') !!}<br> {!! Form::password('password', array('class' => 'form-control')) !!} </div> <div > {!! Form::label('password', 'Confirm Password') !!}<br> {!! Form::password('password_confirmation', array('class' => 'form-control')) !!} </div> {!! Form::submit('Register', array('class' => 'btn btn-primary')) !!} {!! Form::close() !!} </div> @endsection
edit.blade.php
- {{-- resourcesviewsusersedit.blade.php --}}
- @extends('layouts.app')
- @section('title', '| Update User')
- @section('content')
- <divclass='col-lg-4col-lg-offset-4'>
- <h1><iclass='fafa-user-plus'></i> Update {{$user->name}}</h1>
- <hr>
- {{ Form::model($user, array('route' => array('users.update', $user->id), 'method' => 'PUT')) }}
- <divclass="form-group @if ($errors->has('name')) has-error @endif">
- {{ Form::label('name', 'Name') }}
- {{ Form::text('name', null, array('class' => 'form-control')) }}
- </div>
- <divclass="form-group @if ($errors->has('email')) has-error @endif">
- {{ Form::label('email', 'Email') }}
- {{ Form::email('email', null, array('class' => 'form-control')) }}
- </div>
- <h5><b>Assign Role</b></h5>
- <divclass="form-group @if ($errors->has('roles')) has-error @endif">
- @foreach ($roles as $role)
- {{ Form::checkbox('roles[]', $role->id, $user->roles ) }}
- {{ Form::label($role->name, ucfirst($role->name)) }}<br>
- @endforeach
- </div>
- <divclass="form-group @if ($errors->has('password')) has-error @endif">
- {{ Form::label('password', 'Password') }}<br>
- {{ Form::password('password', array('class' => 'form-control')) }}
- </div>
- <divclass="form-group @if ($errors->has('password')) has-error @endif">
- {{ Form::label('password', 'Confirm Password') }}<br>
- {{ Form::password('password_confirmation', array('class' => 'form-control')) }}
- </div>
- {{ Form::submit('Update', array('class' => 'btn btn-primary')) }}
- {{ Form::close() }}
- </div>
- @endsection
{{-- resourcesviewsusersedit.blade.php --}} @extends('layouts.app') @section('title', '| Update User') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-user-plus'></i> Update {{$user->name}}</h1> <hr> {{ Form::model($user, array('route' => array('users.update', $user->id), 'method' => 'PUT')) }} <div > {{ Form::label('name', 'Name') }} {{ Form::text('name', null, array('class' => 'form-control')) }} </div> <div > {{ Form::label('email', 'Email') }} {{ Form::email('email', null, array('class' => 'form-control')) }} </div> <h5><b>Assign Role</b></h5> <div > @foreach ($roles as $role) {{ Form::checkbox('roles[]', $role->id, $user->roles ) }} {{ Form::label($role->name, ucfirst($role->name)) }}<br> @endforeach </div> <div > {{ Form::label('password', 'Password') }}<br> {{ Form::password('password', array('class' => 'form-control')) }} </div> <div > {{ Form::label('password', 'Confirm Password') }}<br> {{ Form::password('password_confirmation', array('class' => 'form-control')) }} </div> {{ Form::submit('Update', array('class' => 'btn btn-primary')) }} {{ Form::close() }} </div> @endsection
Role Management Module
Now add following code in RoleController.php
to create new role.
RoleController.php
- <?php
- namespace AppHttpControllers;
- use AppRole;
- use AppPermission;
- use IlluminateHttpRequest;
- class RoleController extends Controller
- {
- public function__construct()
- {
- $this->middleware('auth');
- }
- public functionindex()
- {
- $roles= Role::all();
- returnview('roles.index',compact('roles'));
- }
- /**
- * Show the form for creating a new resource.
- *
- * @return IlluminateHttpResponse
- */
- public functioncreate()
- {
- $permissions= Permission::all();//Get all permissions
- returnview('roles.create',compact('permissions'));
- }
- /**
- * Store a newly created resource in storage.
- *
- * @param IlluminateHttpRequest $request
- * @return IlluminateHttpResponse
- */
- public functionstore(Request $request)
- {
- $this->validate($request,[
- 'name'=>'required|unique:roles|max:10',
- 'permissions'=>'required',
- ]
- );
- $role=newRole();
- $role->name =$request->name;
- $role->save();
- if($request->permissions <>''){
- $role->permissions()->attach($request->permissions);
- }
- returnredirect()->route('roles.index')->with('success','Roles added successfully');
- }
- public functionedit($id){
- $role= Role::findOrFail($id);
- $permissions= Permission::all();
- returnview('roles.edit',compact('role','permissions'));
- }
- /**
- * Update the specified resource in storage.
- *
- * @param IlluminateHttpRequest $request
- * @param AppRole $role
- * @return IlluminateHttpResponse
- */
- public functionupdate(Request $request,$id)
- {
- $role= Role::findOrFail($id);//Get role with the given id
- //Validate name and permission fields
- $this->validate($request,[
- 'name'=>'required|max:10|unique:roles,name,'.$id,
- 'permissions'=>'required',
- ]);
- $input=$request->except(['permissions']);
- $role->fill($input)->save();
- if($request->permissions <>''){
- $role->permissions()->sync($request->permissions);
- }
- returnredirect()->route('roles.index')->with('success','Roles updated successfully');
- }
- /**
- * Remove the specified resource from storage.
- *
- * @param AppRole $role
- * @return IlluminateHttpResponse
- */
- public functiondestroy($id)
- {
- $role= Role::findOrFail($id);
- $role->delete();
- returnredirect()->route('roles.index')
- ->with('success',
- 'Role deleted successfully!');
- }
- }
<?php namespace AppHttpControllers; use AppRole; use AppPermission; use IlluminateHttpRequest; class RoleController extends Controller { public function __construct() { $this->middleware('auth'); } public function index() { $roles = Role::all(); return view('roles.index',compact('roles')); } /** * Show the form for creating a new resource. * * @return IlluminateHttpResponse */ public function create() { $permissions = Permission::all();//Get all permissions return view('roles.create', compact('permissions')); } /** * Store a newly created resource in storage. * * @param IlluminateHttpRequest $request * @return IlluminateHttpResponse */ public function store(Request $request) { $this->validate($request, [ 'name'=>'required|unique:roles|max:10', 'permissions' =>'required', ] ); $role = new Role(); $role->name = $request->name; $role->save(); if($request->permissions <> ''){ $role->permissions()->attach($request->permissions); } return redirect()->route('roles.index')->with('success','Roles added successfully'); } public function edit($id) { $role = Role::findOrFail($id); $permissions = Permission::all(); return view('roles.edit', compact('role', 'permissions')); } /** * Update the specified resource in storage. * * @param IlluminateHttpRequest $request * @param AppRole $role * @return IlluminateHttpResponse */ public function update(Request $request,$id) { $role = Role::findOrFail($id);//Get role with the given id //Validate name and permission fields $this->validate($request, [ 'name'=>'required|max:10|unique:roles,name,'.$id, 'permissions' =>'required', ]); $input = $request->except(['permissions']); $role->fill($input)->save(); if($request->permissions <> ''){ $role->permissions()->sync($request->permissions); } return redirect()->route('roles.index')->with('success','Roles updated successfully'); } /** * Remove the specified resource from storage. * * @param AppRole $role * @return IlluminateHttpResponse */ public function destroy($id) { $role = Role::findOrFail($id); $role->delete(); return redirect()->route('roles.index') ->with('success', 'Role deleted successfully!'); } }
Role View
index.blade.php
- @extends('layouts.app')
- @section('title', '| Roles')
- @section('content')
- <divclass="col-lg-10 col-lg-offset-1">
- <h1><iclass="fa fa-key"></i> Roles Management
- <ahref="{{ route('users.index') }}"class="btn btn-default pull-right">Users</a>
- <ahref="{{ route('permissions.index') }}"class="btn btn-default pull-right">Permissions</a>
- <ahref="{{ URL::to('roles/create') }}"class="btn btn-success">Add Role</a>
- </h1>
- <hr>
- <divclass="table-responsive">
- <tableclass="table table-bordered table-striped">
- <thead>
- <tr>
- <th>Role</th>
- <th>Permissions</th>
- <th>Action</th>
- </tr>
- </thead>
- <tbody>
- @foreach ($roles as $role)
- <tr>
- <td>{{ $role->name }}</td>
- <td>{{ str_replace(array('[',']','"'),'', $role->permissions()->pluck('name')) }}</td>
- <td>
- <ahref="{{ URL::to('roles/'.$role->id.'/edit') }}"class="btn btn-warning pull-left">Edit</a>
- {!! Form::open(['method' => 'DELETE', 'route' => ['roles.destroy', $role->id] ]) !!}
- {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
- {!! Form::close() !!}
- </td>
- </tr>
- @endforeach
- </tbody>
- </table>
- </div>
- </div>
- @endsection
@extends('layouts.app') @section('title', '| Roles') @section('content') <div > <h1><i ></i> Roles Management <a href="{{ route('users.index') }}" >Users</a> <a href="{{ route('permissions.index') }}" >Permissions</a> <a href="{{ URL::to('roles/create') }}" >Add Role</a> </h1> <hr> <div > <table > <thead> <tr> <th>Role</th> <th>Permissions</th> <th>Action</th> </tr> </thead> <tbody> @foreach ($roles as $role) <tr> <td>{{ $role->name }}</td> <td>{{ str_replace(array('[',']','"'),'', $role->permissions()->pluck('name')) }}</td> <td> <a href="{{ URL::to('roles/'.$role->id.'/edit') }}" >Edit</a> {!! Form::open(['method' => 'DELETE', 'route' => ['roles.destroy', $role->id] ]) !!} {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} </td> </tr> @endforeach </tbody> </table> </div> </div> @endsection
create.blade.php
- {{-- resourcesviewsrolescreate.blade.php --}}
- @extends('layouts.app')
- @section('title', '| Create Role')
- @section('content')
- <divclass='col-lg-4col-lg-offset-4'>
- <h1><iclass='fafa-key'></i> Create Role</h1>
- <hr>
- {{ Form::open(array('url' => 'roles')) }}
- <divclass="form-group">
- {{ Form::label('name', 'Name') }}
- {{ Form::text('name', null, array('class' => 'form-control')) }}
- </div>
- <h5><b>Assign Permissions</b></h5>
- <divclass='form-group'>
- @foreach ($permissions as $permission)
- {{ Form::checkbox('permissions[]', $permission->id ) }}
- {{ Form::label($permission->name, ucfirst($permission->name)) }}<br>
- @endforeach
- </div>
- {{ Form::submit('Save', array('class' => 'btn btn-primary')) }}
- {{ Form::close() }}
- </div>
- @endsection
{{-- resourcesviewsrolescreate.blade.php --}} @extends('layouts.app') @section('title', '| Create Role') @section('content') <div class='col-lg-4 col-lg-offset-4'> <h1><i class='fa fa-key'></i> Create Role</h1> <hr> {{ Form::open(array('url' => 'roles')) }} <div > {{ Form::label('name', 'Name') }} {{ Form::text('name', null, array('class' => 'form-control')) }} </div> <h5><b>Assign Permissions</b></h5> <div class='form-group'> @foreach ($permissions as $permission) {{ Form::checkbox('permissions[]', $permission->id ) }} {{ Form::label($permission->name, ucfirst($permission->name)) }}<br> @endforeach </div> {{ Form::submit('Save', array('class' => 'btn btn-primary')) }} {{ Form::close() }} </div> @endsection
edit.blade.php
- @extends('layouts.app')
- @section('title', '| Update Role')
- @section('content')
- <divclass='col-md-4col-md-offset-4'>
- <h1><iclass='fafa-key'></i> Update Role: {{$role->name}}</h1>
- <hr>
- {{ Form::model($role, array('route' => array('roles.update', $role->id), 'method' => 'PUT')) }}
- <divclass="form-group">
- {{ Form::label('name', 'Role Name') }}
- {{ Form::text('name', null, array('class' => 'form-control')) }}
- </div>
- <h3>Assign Permissions</h3>
- @foreach ($permissions as $permission)
- {{Form::checkbox('permissions[]', $permission->id, $role->permissions ) }}
- {{Form::label($permission->name, ucfirst($permission->name)) }}<br>
- @endforeach
- <br>
- {{ Form::submit('Edit', array('class' => 'btn btn-primary')) }}
- {{ Form::close() }}
- </div>
- @endsection
@extends('layouts.app') @section('title', '| Update Role') @section('content') <div class='col-md-4 col-md-offset-4'> <h1><i class='fa fa-key'></i> Update Role: {{$role->name}}</h1> <hr> {{ Form::model($role, array('route' => array('roles.update', $role->id), 'method' => 'PUT')) }} <div > {{ Form::label('name', 'Role Name') }} {{ Form::text('name', null, array('class' => 'form-control')) }} </div> <h3>Assign Permissions</h3> @foreach ($permissions as $permission) {{Form::checkbox('permissions[]', $permission->id, $role->permissions ) }} {{Form::label($permission->name, ucfirst($permission->name)) }}<br> @endforeach <br> {{ Form::submit('Edit', array('class' => 'btn btn-primary')) }} {{ Form::close() }} </div> @endsection
Permission Management Module
Add following code in PermissionController.php.
- <?php
- namespace AppHttpControllers;
- use AppPermission;
- use AppRole;
- use IlluminateHttpRequest;
- class PermissionController extends Controller
- {
- public function__construct()
- {
- $this->middleware('auth');
- }
- public functionindex()
- {
- $permissions= Permission::all();
- returnview('permissions.index',compact('permissions'));
- }
- /**
- * Show the form for creating a new resource.
- *
- * @return IlluminateHttpResponse
- */
- public functioncreate()
- {
- $roles= Role::get();//Get all roles
- returnview('permissions.create',compact('roles'));
- }
- /**
- * Store a newly created resource in storage.
- *
- * @param IlluminateHttpRequest $request
- * @return IlluminateHttpResponse
- */
- public functionstore(Request $request)
- {
- $this->validate($request,[
- 'name'=>'required|max:40',
- ]);
- $permission=newPermission();
- $permission->name =$request->name;
- $permission->save();
- if($request->roles <>''){
- foreach($request->roles as$key=>$value){
- $role= Role::find($value);
- $role->permissions()->attach($permission);
- }
- }
- returnredirect()->route('permissions.index')->with('success','Permission added successfully');
- }
- public functionedit(Permission $permission)
- {
- returnview('permissions.edit',compact('permission'));
- }
- /**
- * Update the specified resource in storage.
- *
- * @param IlluminateHttpRequest $request
- * @param AppPermission $permission
- * @return IlluminateHttpResponse
- */
- public functionupdate(Request $request, Permission $permission)
- {
- $this->validate($request,[
- 'name'=>'required',
- ]);
- $permission->name=$request->name;
- $permission->save();
- returnredirect()->route('permissions.index')
- ->with('success',
- 'Permission'.$permission->name.' updated!');
- }
- /**
- * Remove the specified resource from storage.
- *
- * @param AppPermission $permission
- * @return IlluminateHttpResponse
- */
- public functiondestroy(Permission $permission)
- {
- $permission->delete();
- returnredirect()->route('permissions.index')
- ->with('success',
- 'Permission deleted successfully!');
- }
- }
<?php namespace AppHttpControllers; use AppPermission; use AppRole; use IlluminateHttpRequest; class PermissionController extends Controller { public function __construct() { $this->middleware('auth'); } public function index() { $permissions = Permission::all(); return view('permissions.index',compact('permissions')); } /** * Show the form for creating a new resource. * * @return IlluminateHttpResponse */ public function create() { $roles = Role::get(); //Get all roles return view('permissions.create',compact('roles')); } /** * Store a newly created resource in storage. * * @param IlluminateHttpRequest $request * @return IlluminateHttpResponse */ public function store(Request $request) { $this->validate($request, [ 'name'=>'required|max:40', ]); $permission = new Permission(); $permission->name = $request->name; $permission->save(); if ($request->roles <> '') { foreach ($request->roles as $key=>$value) { $role = Role::find($value); $role->permissions()->attach($permission); } } return redirect()->route('permissions.index')->with('success','Permission added successfully'); } public function edit(Permission $permission) { return view('permissions.edit', compact('permission')); } /** * Update the specified resource in storage. * * @param IlluminateHttpRequest $request * @param AppPermission $permission * @return IlluminateHttpResponse */ public function update(Request $request, Permission $permission) { $this->validate($request, [ 'name'=>'required', ]); $permission->name=$request->name; $permission->save(); return redirect()->route('permissions.index') ->with('success', 'Permission'. $permission->name.' updated!'); } /** * Remove the specified resource from storage. * * @param AppPermission $permission * @return IlluminateHttpResponse */ public function destroy(Permission $permission) { $permission->delete(); return redirect()->route('permissions.index') ->with('success', 'Permission deleted successfully!'); } }
index.blade.php
- {{-- resourcesviewspermissionsindex.blade.php --}}
- @extends('layouts.app')
- @section('title', '| Permissions')
- @section('content')
- <divclass="col-md-10 col-md-offset-1">
- <h1><iclass="fa fa-key"></i>Permissions Management
- <ahref="{{ route('users.index') }}"class="btn btn-default pull-right">Users</a>
- <ahref="{{ route('roles.index') }}"class="btn btn-default pull-right">Roles</a>
- <ahref="{{ URL::to('permissions/create') }}"class="btn btn-success">Add Permission</a>
- </h1>
- <hr>
- <divclass="table-responsive">
- <tableclass="table table-bordered table-striped">
- <thead>
- <tr>
- <th>Permissions</th>
- <th>Action</th>
- </tr>
- </thead>
- <tbody>
- @foreach ($permissions as $permission)
- <tr>
- <td>{{ $permission->name }}</td>
- <td>
- <ahref="{{ URL::to('permissions/'.$permission->id.'/edit') }}"class="btn btn-warning pull-left">Edit</a>
- {!! Form::open(['method' => 'DELETE', 'route' => ['permissions.destroy', $permission->id] ]) !!}
- {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
- {!! Form::close() !!}
- </td>
- </tr>
- @endforeach
- </tbody>
- </table>
- </div>
- </div>
- @endsection
{{-- resourcesviewspermissionsindex.blade.php --}} @extends('layouts.app') @section('title', '| Permissions') @section('content') <div > <h1><i ></i>Permissions Management <a href="{{ route('users.index') }}" >Users</a> <a href="{{ route('roles.index') }}" >Roles</a> <a href="{{ URL::to('permissions/create') }}" >Add Permission</a> </h1> <hr> <div > <table > <thead> <tr> <th>Permissions</th> <th>Action</th> </tr> </thead> <tbody> @foreach ($permissions as $permission) <tr> <td>{{ $permission->name }}</td> <td> <a href="{{ URL::to('permissions/'.$permission->id.'/edit') }}" >Edit</a> {!! Form::open(['method' => 'DELETE', 'route' => ['permissions.destroy', $permission->id] ]) !!} {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} </td> </tr> @endforeach </tbody> </table> </div> </div> @endsection
create.blade.php
- @extends('layouts.app')
- @section('title', '| Create Permission')
- @section('content')
- <divclass='col-md-4col-md-offset-4'>
- <h1><iclass='fafa-key'></i> Create New Permission</h1>
- <br>
- {{ Form::open(array('url' => 'permissions')) }}
- <divclass="form-group">
- {{ Form::label('name', 'Name') }}
- {{ Form::text('name', '', array('class' => 'form-control')) }}
- </div><br>
- @if(!$roles->isEmpty())
- <h3>Assign Permission to Roles</h3>
- @foreach ($roles as $role)
- {{ Form::checkbox('roles[]', $role->id ) }}
- {{ Form::label($role->name, ucfirst($role->name)) }}<br>
- @endforeach
- @endif
- <br>
- {{ Form::submit('Save', array('class' => 'btn btn-primary')) }}
- {{ Form::close() }}
- </div>
- @endsection
@extends('layouts.app') @section('title', '| Create Permission') @section('content') <div class='col-md-4 col-md-offset-4'> <h1><i class='fa fa-key'></i> Create New Permission</h1> <br> {{ Form::open(array('url' => 'permissions')) }} <div > {{ Form::label('name', 'Name') }} {{ Form::text('name', '', array('class' => 'form-control')) }} </div><br> @if(!$roles->isEmpty()) <h3>Assign Permission to Roles</h3> @foreach ($roles as $role) {{ Form::checkbox('roles[]', $role->id ) }} {{ Form::label($role->name, ucfirst($role->name)) }}<br> @endforeach @endif <br> {{ Form::submit('Save', array('class' => 'btn btn-primary')) }} {{ Form::close() }} </div> @endsection
edit.blade.php
- @extends('layouts.app')
- @section('title', '| Update Permission')
- @section('content')
- <divclass='col-md-4col-md-offset-4'>
- <h1><iclass='fafa-key'></i> Update {{$permission->name}}</h1>
- <br>
- {{ Form::model($permission, array('route' => array('permissions.update', $permission->id), 'method' => 'PUT')) }}
- <divclass="form-group">
- {{ Form::label('name', 'Permission Name') }}
- {{ Form::text('name', null, array('class' => 'form-control')) }}
- </div>
- <br>
- {{ Form::submit('Update', array('class' => 'btn btn-primary')) }}
- {{ Form::close() }}
- </div>
- @endsection
@extends('layouts.app') @section('title', '| Update Permission') @section('content') <div class='col-md-4 col-md-offset-4'> <h1><i class='fa fa-key'></i> Update {{$permission->name}}</h1> <br> {{ Form::model($permission, array('route' => array('permissions.update', $permission->id), 'method' => 'PUT')) }} <div > {{ Form::label('name', 'Permission Name') }} {{ Form::text('name', null, array('class' => 'form-control')) }} </div> <br> {{ Form::submit('Update', array('class' => 'btn btn-primary')) }} {{ Form::close() }} </div> @endsection
Post Management Module
app/Http/Controllers/PostController.php
- <?php
- namespace AppHttpControllers;
- use AppPost;
- use IlluminateHttpRequest;
- class PostController extends Controller
- {
- public function__construct()
- {
- $this->middleware('auth');
- }
- public functionindex()
- {
- $posts= Post::latest()->paginate(10);
- returnview('posts.index',compact('posts'));
- }
- }
<?php namespace AppHttpControllers; use AppPost; use IlluminateHttpRequest; class PostController extends Controller { public function __construct() { $this->middleware('auth'); } public function index() { $posts = Post::latest()->paginate(10); return view('posts.index', compact('posts')); } }
Post View
Now create index.blade.php file in resourcesviewspostsindex.blade.php.
- @extends('layouts.app')
- @section('content')
- <divclass="container">
- <divclass="row">
- <divclass="col-md-10 col-md-offset-1">
- <divclass="panel panel-default">
- <divclass="panel-heading">
- <h3>Posts Management</h3>
- </div>
- <divclass="panel-body">
- <divclass="table-responsive">
- <tableclass="table table-bordered table-striped">
- <thead>
- <tr>
- <th>Title</th>
- <th>Body</th>
- <th>Action</th>
- </tr>
- </thead>
- <tbody>
- @foreach ($posts as $post)
- <tr>
- <td>{{ $post->title }}</td>
- <td>{{ $post->body }}</td>
- <td>
- @can('editPost')
- <ahref="{{ route('posts.edit', $post->id) }}"class="btn btn-info pull-left">Edit</a>
- @endcan
- @can('deletePost')
- {!! Form::open(['method' => 'DELETE', 'route' => ['posts.destroy', $post->id] ]) !!}
- {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
- {!! Form::close() !!}
- @endcan
- </td>
- </tr>
- @endforeach
- </tbody>
- </table>
- </div>
- </div>
- </div>
- <divclass="text-center">
- {!! $posts->render() !!}
- </div>
- </div>
- </div>
- </div>
- @endsection
@extends('layouts.app') @section('content') <div > <div > <div > <div > <div > <h3>Posts Management</h3> </div> <div > <div > <table > <thead> <tr> <th>Title</th> <th>Body</th> <th>Action</th> </tr> </thead> <tbody> @foreach ($posts as $post) <tr> <td>{{ $post->title }}</td> <td>{{ $post->body }}</td> <td> @can('editPost') <a href="{{ route('posts.edit', $post->id) }}" >Edit</a> @endcan @can('deletePost') {!! Form::open(['method' => 'DELETE', 'route' => ['posts.destroy', $post->id] ]) !!} {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} @endcan </td> </tr> @endforeach </tbody> </table> </div> </div> </div> <div > {!! $posts->render() !!} </div> </div> </div> </div> @endsection
That’s it..
You can restrict routes for “User” role using middleware.
In middleware, We will authenticate the current user if user has “Admin” role then User will have full access.
Middleware
- <?php
- namespace AppHttpMiddleware;
- use Closure;
- use IlluminateSupportFacadesAuth;
- class PermissionMiddleware {
- public functionhandle($request, Closure $next){
- if(Auth::user()->hasRole('Admin'))//If user has admin role
- {
- return$next($request);
- }
- if(Auth::user()->hasRole('User'))//If user has user role
- {
- if($request->is('posts/create'))//If user is creating a post
- {
- if(!Auth::user()->hasPermissionTo('addPost'))
- {
- abort('401');
- }
- else{
- return$next($request);
- }
- }
- }
- return$next($request);
- }
- }
<?php namespace AppHttpMiddleware; use Closure; use IlluminateSupportFacadesAuth; class PermissionMiddleware { public function handle($request, Closure $next) { if (Auth::user()->hasRole('Admin')) //If user has admin role { return $next($request); } if (Auth::user()->hasRole('User')) //If user has user role { if ($request->is('posts/create'))//If user is creating a post { if (!Auth::user()->hasPermissionTo('addPost')) { abort('401'); } else { return $next($request); } } } return $next($request); } }
Now add the PermissionMiddleware::class
to $routeMiddleware
property in app/Http/kernel.php :
- protected $routeMiddleware=[
- ....
- 'has_permission'=>AppHttpMiddlewarePermissionMiddleware::class,
- ];
protected $routeMiddleware = [ .... 'has_permission' => AppHttpMiddlewarePermissionMiddleware::class, ];
In middleware, I redirect to user to 401 custom error page if the user does not have rights to access routes.
401.blade.php
- {{-- resourcesviewserrors401.blade.php --}}
- @extends('layouts.app')
- @section('content')
- <divclass='col-md-4col-md-offset-4'>
- <h3><center>401<br>
- You do not have permission</center></h3>
- </div>
- @endsection
{{-- resourcesviewserrors401.blade.php --}} @extends('layouts.app') @section('content') <div class='col-md-4 col-md-offset-4'> <h3><center>401<br> You do not have permission</center></h3> </div> @endsection
Now you can set the middleware to route group like this :
- Route::group(['middleware'=>['auth','has_permission']],function(){
- });
Route::group( ['middleware' => ['auth','has_permission']], function() { });
Hope this code and post will helped you for implement Laravel 5.4 User Role and Permissions (ACL) with Spatie Laravel-Permission Middlware. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs