Download as pdf or txt
Download as pdf or txt
You are on page 1of 88

QCode (https://www.qcode.

in/)
All about Full Stack Web Development

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Home (http://www.qcode.in)

Easy roles and permissions in


About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)
Laravel 5
By Mohd Saqueib (https://www.qcode.in/author/qcode/) May 1, 2017 under Laravel
(https://www.qcode.in/category/laravel/)

Laravel comes with Authentication and Authorization out of the box, I have implemented many role
and permissions based system in the past, using laravel, it’s peace of cake. In this post, we are going to
implement a fully working and extensible roles and permissions on laravel 5. When we nish we will
have a starter kit which we can use for our any future project which needs roles and permissions
based access control (ACL).

Laravel Permissions
Although laravel comes with Policies to handle the authorization I wanted to have an option to just
create permissions in the database which we can manage by a UI in the admin panel, pretty standard.
we can implement our own role and permission from scratch but I am going to use spatie/laravel-
permission (https://github.com/spatie/laravel-permission) package for this. This package was inspired
by Je rey ways screencast and it’s very well maintained and very easy to use. It has everything we
need and plays very well with Laravel Gate and Policies implementations.

/
QCode (https://www.qcode.in/)
All about Full Stack Web Development

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Home (http://www.qcode.in)

About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)

Source Code Laravel 5.4 (https://github.com/saqueib/roles-permissions-laravel)

Source Code Laravel 5.7 (https://github.com/saqueib/roles-permissions-laravel/tree/v5.7)

Sca old app


Let’s get started by creating a fresh laravel app by running laravel new rpl or if you don’t have
laravel command line tool, you can use composer to get it  composer create-project --prefer-
dist laravel/laravel rpl . rpl is the name of app which is an abbreviation for Role Permissions
Laravel.

Once the installation is done, make necessary changes in .env so you can connect to a database.

Setup packages
We will use laravel authorization which comes bundled, let’s sca old it using auth:make command. It
will create a fully functional login, register and password reset features. Now that’s done, let’s pull
packages we will need in this app.

Edit your composer.json to add below dependencies.


/
QCode (https://www.qcode.in/)
"require": {
All about Full Stack
...Web Development
"spatie/laravel-permission": "^2.1",
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
"laracasts/flash": "^3.0", (https://www.qcode.in/contact/
"laravelcollective/html": "^5.3.0"
},
Home (http://www.qcode.in)

About (https://www.qcode.in/about/)
Apart from permissions package, I have also grabbed ash (https://github.com/laracasts/ ash) to
Contact
show noti (https://www.qcode.in/contact/)
cation alerts and laravelcollective html (https://laravelcollective.com/docs/5.3/html)to
create forms with the option to model bind them.

Expert MUMPS Developers (GTM -


InterSystems) 25+ years exp.
AdInterSystems Caché Certi ed Expert
Ad Programming, Design, Conversions
4wtech.com

Learn more

Now Add them in ServiceProvider and in aliases array, open config/app.php

'providers' => [
...
Spatie\Permission\PermissionServiceProvider::class,
Laracasts\Flash\FlashServiceProvider::class,
Collective\Html\HtmlServiceProvider::class,
...
],

'aliases' => [
...
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
]

/
QCode (https://www.qcode.in/)
All about Full Stack Web Development

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Home (http://www.qcode.in)
Cool, now let’s start by publishing migration which comes from permissions package, which will create

Aboutfor(https://www.qcode.in/about/)
tables roles and permissions.

Contact (https://www.qcode.in/contact/)

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --

Expert MUMPS Developers (GTM -


InterSystems) 25+ years exp.
Ad InterSystems Caché Certi ed Expert
Ad Programming, Design, Conversions
4wtech.com

Learn more

Great, now we need to create our Resource, I am going to create Post, Role, Permission models with
resource controller. User model is already present so we will use it.

// Create Post model with migration and resource controller


php artisan make:model Post -m -c --resource

// 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

/
Dedicated Hosting
QCode (https://www.qcode.in/)
All about Full Stack Web Development AdYour project deserves the perfect setup.
100% exible hardware con gurations!
Ad
Home About Contact
(http://www.qcode.in) velia.net
(https://www.qcode.in/about/) (https://www.qcode.in/contact/

Open
Home (http://www.qcode.in)
Spatie\Permission already have role and permissions model, we will just extend them in order to do

About
any (https://www.qcode.in/about/)
changes if needed in future.

Contact (https://www.qcode.in/contact/)

// Permission Model
class Permission extends \Spatie\Permission\Models\Permission { }

// Role Model
class Role extends \Spatie\Permission\Models\Role { }

We need to add HasRoles trait provided by the package to give the user all the power of laravel
permissions.

use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable


{
use HasRoles;
...

/
Now we have all the boilerplate out of the way, let’s create simple database seeder so we can build
QCode (https://www.qcode.in/)
and test our app, you can read more about advance database seeding in this post
All(http://www.qcode.in/advance-interactive-database-seeding-in-laravel/),
about Full Stack Web Development open

Home About and add this code.


database/seeds/DatabaseSeeder.php Contact
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Home (http://www.qcode.in)

About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)

/
QCode (https://www.qcode.in/)
public function run()
All about Full
{ Stack Web Development
// Ask for db migration refresh, default is no
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
if ($this->command->confirm('Do (https://www.qcode.in/contact/
you wish to refresh migration before seeding, i
// Call the php artisan migrate:refresh
$this->command->call('migrate:refresh');
Home (http://www.qcode.in)
$this->command->warn("Data cleared, starting from blank database.");
}
About (https://www.qcode.in/about/)
// Seed the default permissions
Contact (https://www.qcode.in/contact/)
$permissions = Permission::defaultPermissions();

foreach ($permissions as $perms) {


Permission::firstOrCreate(['name' => $perms]);
}

$this->command->info('Default Permissions added.');

// Confirm roles needed


if ($this->command->confirm('Create Roles for user, default is admin and user?

// Ask for roles from input


$input_roles = $this->command->ask('Enter roles in comma separate format.',

// Explode roles
$roles_array = explode(',', $input_roles);

// add roles
foreach($roles_array as $role) {
$role = Role::firstOrCreate(['name' => trim($role)]);

if( $role->name == 'Admin' ) {


// assign all permissions
$role->syncPermissions(Permission::all());
$this->command->info('Admin granted all the permissions');
} else {
// for others by default only read access
$role->syncPermissions(Permission::where('name', 'LIKE', 'view_%')-
}
/
QCode (https://www.qcode.in/)
// create one user for each role
All about Full Stack Web Development
$this->createUser($role);
}
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
$this->command->info('Roles ' . $input_roles . ' added successfully');

Home (http://www.qcode.in)
} else {
Role::firstOrCreate(['name' => 'User']);
About (https://www.qcode.in/about/)
$this->command->info('Added only default user role.');
}
Contact (https://www.qcode.in/contact/)
// now lets seed some posts for demo
factory(\App\Post::class, 30)->create();
$this->command->info('Some Posts data seeded.');
$this->command->warn('All done :)');
}

/**
* 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('Here is your admin details to login:');
$this->command->warn($user->email);
$this->command->warn('Password is "secret"');
}
}

/
QCode (https://www.qcode.in/)
All about Full Stack Web Development

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Home (http://www.qcode.in)
Now add  defaultPermissions in Permissions Model which we have created.

About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)
public static function defaultPermissions()
{
return [
'view_users',
'add_users',
'edit_users',
'delete_users',

'view_roles',
'add_roles',
'edit_roles',
'delete_roles',

'view_posts',
'add_posts',
'edit_posts',
'delete_posts',
];
}

Dedicated Hosting
AdYour project deserves the perfect setup.
100% exible hardware con gurations!
Ad
velia.net

Open
/
Post model factory contains only 2 leds, title and body. You should setup the migration and factory.
QCode (https://www.qcode.in/)
Now run the seeder using php artisan db:seed it should give an admin user which you can use to
All about Full Stack Web Development
login.

Home About Contact


Now you can login with admin user
(http://www.qcode.in) but there is no access control in place,
(https://www.qcode.in/about/) I will create the User
(https://www.qcode.in/contact/
Resource rst.

Create the UserController and add below code.


Home (http://www.qcode.in)

About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)

/
QCode (https://www.qcode.in/)
public function index()
All about
{ Full Stack Web Development
$result = User::latest()->paginate();
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
return view('user.index', compact('result')); (https://www.qcode.in/contact/
}

Home (http://www.qcode.in)
public function create()
{
About (https://www.qcode.in/about/)
$roles = Role::pluck('name', 'id');
return view('user.new', compact('roles'));
Contact (https://www.qcode.in/contact/)
}

public function store(Request $request)


{
$this->validate($request, [
'name' => 'bail|required|min:2',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
'roles' => 'required|min:1'
]);

// hash password
$request->merge(['password' => bcrypt($request->get('password'))]);

// Create the user


if ( $user = User::create($request->except('roles', 'permissions')) ) {
$this->syncPermissions($request, $user);
flash('User has been created.');
} else {
flash()->error('Unable to create user.');
}

return redirect()->route('users.index');
}

public function edit($id)


{
$user = User::find($id);
$roles = Role::pluck('name', 'id');
/
$permissions = Permission::all('name', 'id');
QCode (https://www.qcode.in/)
All about Full Stack Web
return Development compact('user', 'roles', 'permissions'));
view('user.edit',
}
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
public function update(Request $request, $id)
{
Home (http://www.qcode.in)
$this->validate($request, [
'name' => 'bail|required|min:2',
About (https://www.qcode.in/about/)
'email' => 'required|email|unique:users,email,' . $id,
'roles' => 'required|min:1'
Contact]);
(https://www.qcode.in/contact/)

// Get the user


$user = User::findOrFail($id);

// Update user
$user->fill($request->except('roles', 'permissions', 'password'));

// check for password change


if($request->get('password')) {
$user->password = bcrypt($request->get('password'));
}

// Handle the user roles


$this->syncPermissions($request, $user);

$user->save();
flash()->success('User has been updated.');
return redirect()->route('users.index');
}

public function destroy($id)


{
if ( Auth::user()->id == $id ) {
flash()->warning('Deletion of currently logged in user is not allowed :(')->imp
return redirect()->back();
}

if( User::findOrFail($id)->delete() ) {
flash()->success('User has been deleted'); /
} else {
QCode (https://www.qcode.in/)
flash()->success('User not deleted');
All about Full
} Stack Web Development

Home About Contact


return redirect()->back();
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
}

Home (http://www.qcode.in)
private function syncPermissions(Request $request, $user)
{
About (https://www.qcode.in/about/)
// Get the submitted roles
$roles = $request->get('roles', []);
Contact$permissions
(https://www.qcode.in/contact/)
= $request->get('permissions', []);

// Get the roles


$roles = Role::find($roles);

// check for current role changes


if( ! $user->hasAllRoles( $roles ) ) {
// reset all direct permissions for user
$user->permissions()->sync([]);
} else {
// handle permissions
$user->syncPermissions($permissions);
}

$user->syncRoles($roles);
return $user;
}

Everything is commented and self-explanatory, it’s a simple controller to perform CRUD operation with
user level permission override so you can give access to certain permissions for the speci c user.
Now register the route for all the resource controllers.

/
QCode (https://www.qcode.in/)
Route::group( ['middleware' => ['auth']], function() {
All about Full Stack Web Development 'UserController');
Route::resource('users',
Route::resource('roles', 'RoleController');
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
Route::resource('posts', 'PostController'); (https://www.qcode.in/contact/
});

Home (http://www.qcode.in)

About
Go (https://www.qcode.in/about/)
ahead and create the PostController by yourself, you can always access the source code if need
help.
Contact (https://www.qcode.in/contact/)
Authorization
This is the main part, authorization will be in 2 level, rst is at the controller level and second in view
level. In view, if you don’t have permission to add_users then it doesn’t make sense to show Create
button. this can be done using @can('add_users') directive in blade template.

...
@can('add_users')
<a href="{{ route('users.create') }}" class="btn btn-primary btn-sm">
<i class="glyphicon glyphicon-plus-sign"></i> Create

</a>
@endcan
...

Similarly, if you don’t have access to edit_users you should not see the edit button or delete button
in the table.

/
QCode (https://www.qcode.in/)
All about Full Stack Web Development

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Home (http://www.qcode.in)

About (https://www.qcode.in/about/)
<table class="table table-bordered table-striped table-hover" id="data-table">
Contact<thead>
(https://www.qcode.in/contact/)
<tr>
....
<th>Created At</th>
@can('edit_users', 'delete_users')
<th class="text-center">Actions</th>
@endcan
</tr>
</thead>
<tbody>
@foreach($result as $item)
<tr>
...
@can('edit_users')
<td class="text-center">
// action buttons
</td>
@endcan
</tr>
@endforeach
</tbody>
</table>

Now that’s ne, but some malicious user can still directly visit the URL and he will be able to access the
protected route. To prevent that we need protection on controller@method level.

Authorizable Trait

/
We can add $user->can() check in every method to handle authorization but it will make it more
QCode (https://www.qcode.in/)
di cult to maintain and since we will be using this in multiple resource controller it will be good to
All about Full Stack Web Development
extract out this logic in a trait which will handle the authorization automatically, sounds good! let’s do
it.
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Home (http://www.qcode.in)

About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)

/
QCode (https://www.qcode.in/)
namespace App;
All about Full Stack Web Development

trait Authorizable
Home About Contact
(http://www.qcode.in)
{ (https://www.qcode.in/about/) (https://www.qcode.in/contact/
private $abilities = [
'index' => 'view',
Home (http://www.qcode.in)
'edit' => 'edit',
'show' => 'view',
About (https://www.qcode.in/about/)
'update' => 'edit',
'create' => 'add',
Contact (https://www.qcode.in/contact/)
'store' => 'add',
'destroy' => 'delete'
];

/**
* Override of callAction to perform the authorization before
*
* @param $method
* @param $parameters
* @return mixed
*/
public function callAction($method, $parameters)
{
if( $ability = $this->getAbility($method) ) {
$this->authorize($ability);
}

return parent::callAction($method, $parameters);


}

public function getAbility($method)


{
$routeName = explode('.', \Request::route()->getName());
$action = array_get($this->getAbilities(), $method);

return $action ? $action . '_' . $routeName[0] : null;


}

private function getAbilities()


/
{
QCode (https://www.qcode.in/)
return $this->abilities;
All about Full
} Stack Web Development

Home About Contact


public function setAbilities($abilities)
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
{
$this->abilities = $abilities;
Home (http://www.qcode.in)
}
}
About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)
In this trait we have to override the callAction method which gets called by the router to trigger
respective method on the resource controller, that’s good place to check the permission, so we get the
route name in users case it will be users.index, users.store, users.update etc.. we have mapped the
abilities to our resource controller route naming conventions.

what happens is when a user visits route named users.index , it gets translated into  view_users
ability to check against in authorize($ability) method by getAbility() method, when user visits edit
page route users.edit it will be translated as edit_users and so on. by extracting this logic in a Trait
we will be able to apply authorization on any resource controller we wanted.

Add our trait on UserController.

use App\Authorizable;

class UserController extends Controller


{
use Authorizable;
...

That’s it, your controller is protected, the only user who has permissions to visit certain route can
access it.

When user doesn’t have permission they get AuthorizationException exception, which is not very
friendly to end user, let’s handle this in global Handler so we can display a noti cation and send the
user back to dashboard if the try to visit some route which they don’t suppose to access.
/
AuthorizationException Exception Handler
QCode (https://www.qcode.in/)
Open the app/Exceptions/Handler.php and add this in render method
All about Full Stack Web Development

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
public function render($request, Exception $exception)
{
Home (http://www.qcode.in)
if ($exception instanceof AuthorizationException) {
return $this->unauthorized($request, $exception);
About (https://www.qcode.in/about/)
}

Contactreturn
(https://www.qcode.in/contact/)
parent::render($request, $exception);
}

private function unauthorized($request, Exception $exception)


{
if ($request->expectsJson()) {
return response()->json(['error' => $exception->getMessage()], 403);
}

flash()->warning($exception->getMessage());
return redirect()->route('home');
}

This will redirect back to home route with ash noti cation if user doesn’t have access to the action.

Role Management
Let’s create the roles management resource controller. which admin can use to create the new role
and give or change permission to them.

/
QCode (https://www.qcode.in/)
class RoleController extends Controller
All about
{ Full Stack Web Development
use Authorizable;
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
public function index()
{
Home (http://www.qcode.in)
$roles = Role::all();
$permissions = Permission::all();
About (https://www.qcode.in/about/)
return view('role.index', compact('roles', 'permissions'));
Contact (https://www.qcode.in/contact/)
}

public function store(Request $request)


{
$this->validate($request, ['name' => 'required|unique:roles']);

if( Role::create($request->only('name')) ) {
flash('Role Added');
}

return redirect()->back();
}

public function update(Request $request, $id)


{
if($role = Role::findOrFail($id)) {
// admin role has everything
if($role->name === 'Admin') {
$role->syncPermissions(Permission::all());
return redirect()->route('roles.index');
}

$permissions = $request->get('permissions', []);


$role->syncPermissions($permissions);
flash( $role->name . ' permissions has been updated.');
} else {
flash()->error( 'Role with id '. $id .' note found.');
}

/
return redirect()->route('roles.index');
QCode
} (https://www.qcode.in/)
All about
} Full Stack Web Development

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Now lets add the views for role, create resources/views/role/index.blade.php with below markup.

Home (http://www.qcode.in)

About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)

/
QCode (https://www.qcode.in/)
@extends('layouts.app')
All about Full Stack Web Development
@section('title', 'Roles & Permissions')
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
@section('content')
<!-- Modal -->
Home (http://www.qcode.in)
<div class="modal fade" id="roleModal" tabindex="-1" role="dialog" aria-labelledby=
<div class="modal-dialog" role="document">
About (https://www.qcode.in/about/)
{!! Form::open(['method' => 'post']) !!}

Contact (https://www.qcode.in/contact/)
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label
<h4 class="modal-title" id="roleModalLabel">Role</h4>
</div>
<div class="modal-body">
<!-- name Form Input -->
<div class="form-group @if ($errors->has('name')) has-error @endif"
{!! Form::label('name', 'Name') !!}
{!! Form::text('name', null, ['class' => 'form-control', 'place
@if ($errors->has('name')) <p class="help-block">{{ $errors->fi
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">

<!-- Submit Form Button -->


{!! Form::submit('Submit', ['class' => 'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
</div>
</div>
</div>

<div class="row">
<div class="col-md-5">
<h3>Roles</h3>
</div>
<div class="col-md-7 page-action text-right">
/
@can('add_roles')
QCode (https://www.qcode.in/)
<a href="#" class="btn btn-sm btn-success pull-right" data-toggle="moda
All about Full Stack Web Development
@endcan
</div>
Home About Contact
</div>
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Home (http://www.qcode.in)
@forelse ($roles as $role)
{!! Form::model($role, ['method' => 'PUT', 'route' => ['roles.update', $role->
About (https://www.qcode.in/about/)
@if($role->name === 'Admin')
Contact (https://www.qcode.in/contact/)
@include('shared._permissions', [
'title' => $role->name .' Permissions',
'options' => ['disabled'] ])
@else
@include('shared._permissions', [
'title' => $role->name .' Permissions',
'model' => $role ])
@can('edit_roles')
{!! Form::submit('Save', ['class' => 'btn btn-primary']) !!}
@endcan
@endif

{!! Form::close() !!}

@empty
<p>No Roles defined, please run <code>php artisan db:seed</code> to seed some d
@endforelse
@endsection

Let’s add  resources/views/shared/_permissions.blade.php template.

/
QCode (https://www.qcode.in/)
<div class="panel panel-default">
All about Full Stack
<div Web Development
class="panel-heading" role="tab" id="{{ isset($title) ? str_slug($title) : 'p
<h4 class="panel-title">
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
<a role="button" (https://www.qcode.in/contact/
data-toggle="collapse" data-parent="#accordion" href="#dd-
{{ $title or 'Override Permissions' }} {!! isset($user) ? '<span class=
</a>
Home (http://www.qcode.in)
</h4>
</div>
About (https://www.qcode.in/about/)
<div id="dd-{{ isset($title) ? str_slug($title) : 'permissionHeading' }}" class="p
<div class="panel-body">
Contact (https://www.qcode.in/contact/)
<div class="row">
@foreach($permissions as $perm)
<?php
$per_found = null;

if( isset($role) ) {
$per_found = $role->hasPermissionTo($perm->name);
}

if( isset($user)) {
$per_found = $user->hasDirectPermission($perm->name);
}
?>

<div class="col-md-3">
<div class="checkbox">
<label class="{{ str_contains($perm->name, 'delete') ? 'tex
{!! Form::checkbox("permissions[]", $perm->name, $per_f
</label>
</div>
</div>
@endforeach
</div>
</div>
</div>
</div>

/
If you visit now  /roles you can nd will be able to manage the roles and permission.
QCode (https://www.qcode.in/)
All about Full Stack Web Development

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Home (http://www.qcode.in)

About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)

Permissions Management
Permissions are not going to be changed very often in most cases, you can just add them directly into
the database. I am leaving the implementation for this. It’s simple CRUD, if you wanted you can
implement it. One thing we can do to create a command which we can run to create permissions,
something like php artisan auth:permission tasks , which will create 'view_tasks',
'add_tasks', 'edit_tasks', 'delete_tasks' the permissions for tasks model, and if we pass --
remove it will delete permissions on it.

Create our command by running php artisan make:command AuthPermissionCommand .

/
QCode (https://www.qcode.in/)
class AuthPermissionCommand extends Command
All about
{ Full Stack Web Development
protected $signature = 'auth:permission {name} {--R|remove}';
Home About Contact
(http://www.qcode.in)
... (https://www.qcode.in/about/) (https://www.qcode.in/contact/

public function handle()


Home (http://www.qcode.in)
{
$permissions = $this->generatePermissions();
About (https://www.qcode.in/about/)
// check if its remove
Contact (https://www.qcode.in/contact/)
if( $is_remove = $this->option('remove') ) {
// remove permission
if( Permission::where('name', 'LIKE', '%'. $this->getNameArgument())->delet
$this->warn('Permissions ' . implode(', ', $permissions) . ' deleted.')
} else {
$this->warn('No permissions for ' . $this->getNameArgument() .' found!
}

} else {
// create permissions
foreach ($permissions as $permission) {
Permission::firstOrCreate(['name' => $permission ]);
}

$this->info('Permissions ' . implode(', ', $permissions) . ' created.');


}

// sync role for admin


if( $role = Role::where('name', 'Admin')->first() ) {
$role->syncPermissions(Permission::all());
$this->info('Admin permissions');
}
}

private function generatePermissions()


{
$abilities = ['view', 'add', 'edit', 'delete'];
$name = $this->getNameArgument();

/
return array_map(function($val) use ($name) {
QCodereturn
(https://www.qcode.in/)
$val . '_'. $name;
All about Full Stack
}, Web Development
$abilities);
}
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
private function getNameArgument()
{
Home (http://www.qcode.in)
return strtolower(str_plural($this->argument('name')));
}
About
} (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)

Our command is ready, next let’s register it in Kernel, open the app/Console/Kernel.php and add.

App\Console\Commands\AuthPermissionCommand;

class Kernel extends ConsoleKernel


{
protected $commands = [
AuthPermissionCommand::class
];
...

The auth:permission command is ready, now you can run it to add/remove permissions.

If you added permissions manually in the db, don’t forget to run  php artisan
cache:forget spatie.permission.cache , otherwise new permissions wont work.

Finally, we have a starter kit which you can use for any new project required roles and permissions.
Check the source code & I hope you found it useful, let me know in the comments if you have any
question.
/
Source Code Laravel 5.4 (https://github.com/saqueib/roles-permissions-laravel)
QCode (https://www.qcode.in/)
All about Full Stack Web Development
Source Code Laravel 5.7 (https://github.com/saqueib/roles-permissions-laravel/tree/v5.7)

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
Share this:

 (https://www.qcode.in/easy-roles-and-permissions-in-laravel-5-4/?share=email&nb=1)
Home (http://www.qcode.in)
 (https://www.qcode.in/easy-roles-and-permissions-in-laravel-5-4/?share=twitter&nb=1)

 (https://www.qcode.in/about/)
About
(https://www.qcode.in/easy-roles-and-permissions-in-laravel-5-4/?share=facebook&nb=1)

 (https://www.qcode.in/contact/)
(https://www.qcode.in/easy-roles-and-permissions-in-laravel-5-4/?share=linkedin&nb=1)
Contact
 (https://www.qcode.in/easy-roles-and-permissions-in-laravel-5-4/?share=reddit&nb=1)

 (https://www.qcode.in/easy-roles-and-permissions-in-laravel-5-4/?share=pinterest&nb=1)

 (https://www.qcode.in/easy-roles-and-permissions-in-laravel-5-4/?share=jetpack-whatsapp&nb=1)

Related

(https://www.qcode.in/advance- (https://www.qcode.in/subscrip (https://www.qcode.in/ready-to-


interactive-database-seeding- tion-with-coupon-using-laravel- use-uuid-in-your-next-laravel-
in-laravel/) cashier-stripe/) app/)
Advance interactive database Subscription with coupon using Ready to use UUID in your next
seeding in Laravel Laravel Cashier & Stripe laravel app?
(https://www.qcode.in/advance- (https://www.qcode.in/subscription- (https://www.qcode.in/ready-to-use-
interactive-database-seeding-in- with-coupon-using-laravel-cashier- uuid-in-your-next-laravel-app/)
laravel/) stripe/) November 16, 2017
December 20, 2016 January 7, 2017 In "Laravel"
In "Laravel" In "Laravel"

Tags: authorization (https://www.qcode.in/tag/authorization/), laravel (https://www.qcode.in/tag/laravel/),


permissions (https://www.qcode.in/tag/permissions/), roles (https://www.qcode.in/tag/roles/), user management
(https://www.qcode.in/tag/user-management/)

Build complete RSS feed reader app – Front-end with Vue.js, Vuex & Element UI
(https://www.qcode.in/build-complete-rss-feed-reader-app-front-end-with-vue-js-vuex-element-ui/)
Convert Vue.js app to Native desktop app using Electron (https://www.qcode.in/convert-vue-js-app-
native-desktop-app-using-electron/)
/
141 Responses to “Easy roles and permissions in Laravel 5”
QCode (https://www.qcode.in/)
All about Full Stack Web Development
Very nice, thanks for writing this. I’ll add a link to this tutorial in the readme of the
Home — Freek Van der package. About Contact
(http://www.qcode.in)
Herten (https://www.qcode.in/about/) (https://www.qcode.in/contact/
(https://murze.be/)
May 1, 2017
(https://www.qcode.in/easy That will be great, thanks for simple and awesome
Home (http://www.qcode.in)
-roles-and-permissions-in-
laravel-5-4/#comment-16) — Saqueib package for laravel permissions
May 1, 2017
About (https://www.qcode.in/about/)
(https://www.qcode
.in/easy-roles-and-
permissions-in-
Contact (https://www.qcode.in/contact/)
laravel-5-
4/#comment-17)

Really nice tutorial !


— bambamboole This helped me a lot with handling ACL in my new Application
May 1, 2017
(https://www.qcode.in/easy
-roles-and-permissions-in-
laravel-5-4/#comment-18)

Nice Tutorial. It is very helpful.


— Saquib Rizwan
(https://www.cloudway
s.com)
May 4, 2017
(https://www.qcode.in/easy
-roles-and-permissions-in-
laravel-5-4/#comment-19)

I added one custom permission directly to the database (not crud permission) and
— bambamboole the template breaks. Do you have any solution for this?
May 6, 2017
(https://www.qcode.in/easy
-roles-and-permissions-in-
laravel-5-4/#comment-20)
You can always fallback to
— Saqueib @can('your_custom_permissions') in blade template.
May 6, 2017
(https://www.qcode same is true for controller Auth::user()-
.in/easy-roles-and-
>can('your_custom_permissions') or you can use
permissions-in-
laravel-5- authorized like this
4/#comment-21)

/
QCode (https://www.qcode.in/)
$this->authorize('your_custom_permissions');
All about Full Stack Web Development
I would suggest pick a naming convention for route and
Home About permission and stick to it, you can also
Contact
match the
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
$abilities array in Authorizable traits line number 15

for your speci c need.

Home (http://www.qcode.in)
If you need any further help, please share your custom
route and some permissions you wanted to add. by
About (https://www.qcode.in/about/)
default a permission name is made of

Contact (https://www.qcode.in/contact/)
{controller_method}_{route_name} see the trait.

I just added a new permission as an


— example for a custom permission and
bambambo
the route with the role/permissions
ole
May 8, 2017 form broke.
(https://www.
qcode.in/eas
I know how I can authorize against a
y-roles-and- custom permission, but i want the
permissions-
in-laravel-5- custom permission in the permissions
4/#comment-
view with the other permissions 🙂
22)

ok, if you can share the


— permissions you
Mohd
wanted to add, i will try
Saquei
b to reproduce it at my
May 8,
end to better
2017
(https:// understanding.
www.qc
ode.in/e
asy- I need to add these
roles-
directly in database
and-
permissi right?
ons-in-
laravel-
5-
4/#com
ment-
23)

/
QCode (https://www.qcode.in/)
if you can give me the
— permissions you have
All about Full Stack Web Development
Saquei
added that will be very
b
Home About
May 8, helpful to reproduce Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
2017 (https://www.qcode.in/contact/
(https:// this error at my end.
www.qc
ode.in/e
Home (http://www.qcode.in) asy-
roles-
and-— I just
ba added a
About (https://www.qcode.in/about/)
permissi
ons-in- mb
laravel-
new
am
Contact (https://www.qcode.in/contact/)
5-
boo permission
4/#com
le via Sequel
ment-
May
24)
10, Pro called
2017
(http
custom_permissi
s://w nothing
ww.
qcod more.
e.in/
After
easy
- adding this
roles
- permission
and-
the
per
miss permission
ions-
in- template
larav
breaks…
el-5-
4/#c
om
men
t-25)

— Worked
Josh out the
June
8, issue. After
2017
adding a
(http
s://w permission
ww.
qcod
via Sequal
e.in/ Pro you
easy
- need to
roles
-
run `php
and-
per
/
miss
artisan
QCode (https://www.qcode.in/)
ions-
cache:forget in-
larav
All about Full Stack Web Development el-5-
spatie.permission
4/#c
Home About om Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
men (https://www.qcode.in/contact/
t-31)

Home (http://www.qcode.in)

About (https://www.qcode.in/about/)
— Heya, If I
Josh try and
June
Contact (https://www.qcode.in/contact/)
8, add a
2017
custom
(http
s://w permission
ww.
qcod
called
e.in/ ‘access_sta _pan
easy
- it would
roles
-
break the
and- permissions
per
miss blade
ions-
saying .
in-
larav “There is
el-5-
4/#c no
om
permission
men
t-30) named
`access_sta _pa
for guard
`web`.” As
mentioned
I did this
just using
Sequal Pro,
how would
I go about
adding a
custom
permission
that I can

/
assign to
QCode (https://www.qcode.in/)
roles +
All about Full Stack Web Development users?

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Home (http://www.qcode.in)

About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)

Nice tutorial, thank you! It has helped me get ACL working on my new app. I am
— Chris Van Cleve experiencing one small issue though: Trying to use the auth:permission artisan
(https://chris.vanclevefa
command works for creating new permissions, but trying to use the –R or remove
mily.net)
May 14, 2017 option results in “The “–R” option does not exist.” or “Too many arguments,
(https://www.qcode.in/easy
-roles-and-permissions-in-
expected arguments “command” “name”. respectively. Any ideas why I can’t specify
laravel-5-4/#comment-26) remove?

hey Chris, you need to user


— Saqueib
June 9, 2017 php artisan auth:permission Comment -R
(https://www.qcode
.in/easy-roles-and-
or
permissions-in- php artisan auth:permission Comment –remove
laravel-5-
4/#comment-35)
to remove permissions.

Thank You very much 🙂


— Богдан Гдаль
(http://bohdan.com.ua/
)
June 9, 2017
(https://www.qcode.in/easy
-roles-and-permissions-in-
laravel-5-4/#comment-32)

/
— Satish Reddy

QCode (https://www.qcode.in/)
excellent tutorial, it showed me the way. i struck here, where in migrations when i
June 9, 2017
(https://www.qcode.in/easy
see migrations it can create model_has_roles and model_has_permissions tables.
All -roles-and-permissions-in-
about Full Stack Web Development
laravel-5-4/#comment-33)
But when i run the code i am getting errors like ‘base table or view not found. we
Home About
don’t have Contacttable. Please
tables like user_has_roles and user_has_permissions
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
suggest. thank you in advance. thank you

Home (http://www.qcode.in)
Its seems you forgot to ran the migrations, please try

About (https://www.qcode.in/about/)
— Saqueib running it but
June 9, 2017
(https://www.qcode
php artisan migrate
Contact (https://www.qcode.in/contact/)
.in/easy-roles-and-
permissions-in- or
laravel-5-
4/#comment-34) php artisan migrate:refresh

or if you have cloned code from repo you can run the php

artisan db:seed it will prompt u to refresh the

migration.

Let me know how it goes

Hey Saqueib,
— madsem
June 12, 2017 very nice tutorial! Thanks a lot, will use this for my new app.
(https://www.qcode.in/easy
-roles-and-permissions-in-
Quick question: As far as I can see, there is nothing prepared to make queries in a
laravel-5-4/#comment-36)
Controller based on user permissions.

For example on an edit view, include roles for admins, but not for normal users.

How would you do that?

Just rely on @can(‘admin’) in Blade, or actually do two seperate Eloquent queries for
each user role to only include the data they are allowed to see?

hi @madsem:disqus you can query or check for


— Saqueib permission in controller using $user-
June 12, 2017
(https://www.qcode >can('assign_roles')
.in/easy-roles-and-
.
permissions-in-
/
laravel-5-
To show the user roles for admin I would create a custom
QCode (https://www.qcode.in/)
4/#comment-37)
permission and assign it to admin role, and later in blade
All about Full Stack Webview
Development
i would check it by @can(‘assign_roles’) directive.
don’t forget to run php artisan cache:forget
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
spatie.permission.cache to clear the cache. (https://www.qcode.in/contact/

Home (http://www.qcode.in)
got it, thanks 🙂
— madsem
About (https://www.qcode.in/about/)
I think I wasn’t 100% clear with my
June 12, 2017
(https://www.
qcode.in/eas
question.
Contact (https://www.qcode.in/contact/)
y-roles-and-
permissions- I meant: Would you even make
in-laravel-5-
4/#comment- Eloquent queries based on user roles,
38)
or just one query for all data a View
needs, and then only use
@can(‘permission’) in the Blade view
to include/exclude data, or would you
make multiple DB queries, one for
each role? Like what do you think is
best practice here 🙂

Saqueib I believe there are two small


— madsem errors in the Git repo.
June 14, 2017
(https://www.
“`
qcode.in/eas UserController.php
y-roles-and-
permissions-
in-laravel-5- } else {
4/#comment-
39)
// handle permissions

$user-
>syncPermissions($permissions);

}
“`

should be:
“`
… /
}
QCode (https://www.qcode.in/)
// handle permissions
All about Full Stack Web Development

$user-
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
>syncPermissions($permissions); (https://www.qcode.in/contact/

“`

Home (http://www.qcode.in)
otherwise permissions are not
correctly updated when you override
About (https://www.qcode.in/about/)
them on a per user basis.

Contact (https://www.qcode.in/contact/)
And in Handler.php you have
commented out the render() method,
which causes the auth check to throw
an error when a user does an
unauthorized action.

Great Tutorial, I am new in laravel and I am learning how to manage the roles and
— Jonathan Espinosa permissions situation, Can you help to understand how to add new permissions
June 17, 2017
(https://www.qcode.in/easy
and roles? and to martch it with the controllers or routes, I can understand that. I
-roles-and-permissions-in- hope you can help me. sorry for this noob cuestion.
laravel-5-4/#comment-40)

Thanks, If you clone the repo you can add Roles by


— Saqueib running php artisan db:seed . It will ask you to type
June 17, 2017
(https://www.qcode roles in comma separate format, like ‘Admin,User’ will
.in/easy-roles-and-
create these 2 roles. or you can manually add a Role
permissions-in-
laravel-5- directly in roles mysql table.
4/#comment-45)

For permissions you can use another command php

artisan auth:permission Post , it will create

permissions for Post model.

/
Now when you have got roles and permissions ready you
QCode (https://www.qcode.in/)
can add Authorizable trait on a any resource controller to
All about Full Stack Webprotect
Development
it via permissions.

Home … About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
class PostController extends Controller
{

Home (http://www.qcode.in)
use Authorizable;

About (https://www.qcode.in/about/)
I hope it helps you. If you have any question let me know

Contact (https://www.qcode.in/contact/)

When I have upload live server then shown this error ,,


— Morshed Khan Rana
June 23, 2017 (1/1) FatalErrorException
(https://www.qcode.in/easy
-roles-and-permissions-in-
syntax error, unexpected ‘:’, expecting ‘;’ or ‘{‘
laravel-5-4/#comment-47) in PermissionRegistrar.php (line 33)

Please help me , as soon as possible !!!

http://pos.hello-sylhet.com/ (http://pos.hello-sylhet.com/)

It seems something wrong with permissions, directories


— Saqueib within the storage and the bootstrap/cache directories
June 28, 2017
(https://www.qcode
should be writable by your web server. Also run composer
.in/easy-roles-and- update on server
permissions-in-
laravel-5-
4/#comment-50)

when I run this project in localhost


— Morshed then work perfectly but when I upload
Khan Rana
this project host in live server then
July 1, 2017
(https://www. given this error ,, please tell me how
qcode.in/eas
y-roles-and- can I x it !
permissions-
in-laravel-5-
(1/1) FatalErrorException
4/#comment-
52) syntax error, unexpected ‘:’, expecting
‘;’ or ‘{‘
in PermissionRegistrar.php (line 33)
/
http://postest.hello-sylhet.com/
QCode (https://www.qcode.in/)
(http://postest.hello-sylhet.com/)
All about Full Stack Web Development
please reply !!

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
Your web server is
— running old version on
Saquei
Home (http://www.qcode.in) PHP 5.3, try updating it
b
July 7, to PHP >= 5.6.4, this
About (https://www.qcode.in/about/) 2017
should x it
(https://
www.qc

Contact (https://www.qcode.in/contact/)
ode.in/e
asy-
roles-
and-
permissi
ons-in-
laravel-
5-
4/#com
ment-
55)

Great tut. Absolutely try this for a side project. Thanks S.


— Chu Quang Tu
(http://chuquangtu.com
/blog)
June 23, 2017
(https://www.qcode.in/easy
-roles-and-permissions-in-
laravel-5-4/#comment-48)

I am total newbie in laravel, I tried following this tutorial, when I run php artisan
— tahjid ashfaque db:seed, I am getting this error,
June 27, 2017
(https://www.qcode.in/easy
-roles-and-permissions-in-
[SymfonyComponentDebugExceptionFatalThrowableError]
laravel-5-4/#comment-49) Class ‘Permission’ not found
but my Permission model is de ned , please help.
Thank You

/
QCode (https://www.qcode.in/)
It seems a Namespace Issue, make sure you import the
— Mohd Permission Model, by default it will be App\ Permission.
All about Full Stack Web Development
Saqueib
Here is Permissions controller
June 28, 2017
Home(https://www.qcode About
https://github.com/saqueib/roles-permissions- Contact
(http://www.qcode.in)
.in/easy-roles-and- (https://www.qcode.in/about/) (https://www.qcode.in/contact/
permissions-in- laravel/blob/master/app/Permission.php
laravel-5-
(https://github.com/saqueib/roles-permissions-
4/#comment-51)
Home (http://www.qcode.in)
laravel/blob/master/app/Permission.php)

About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)
How can i hide topnav menus.
— Shakir Bhatt
July 10, 2017
(https://www.qcode.in/easy
-roles-and-permissions-in- You can edit master app layout to hide the menu, you can
laravel-5-4/#comment-56)
— Saqueib nd it here https://github.com/saqueib/roles-permissions-
July 10, 2017
(https://www.qcode
laravel/blob/master/resources/views/layouts/app.blade.php#L29
.in/easy-roles-and- (https://github.com/saqueib/roles-permissions-
permissions-in-
laravel-5- laravel/blob/master/resources/views/layouts/app.blade.php#L29)
4/#comment-57)

Thanks for replying.


— Shakir say i have topnav bar form which i
Bhatt
want to hide some link based on user
July 10, 2017
(https://www. type. @can(‘custom_permission’)
qcode.in/eas
y-roles-and- ..@endcan; I am confused with
permissions-
‘custom_permission’. where from
in-laravel-5-
4/#comment- @can() gets this ‘custom_permission’.
58)

{{trans(‘dashboard.security’)}}
— Shakir
Bhatt @can(‘view_roles’)
July 10, 2017
(https://www.
qcode.in/eas
y-roles-and- {{trans(‘dashboard.role_management’)}}
permissions-
in-laravel-5-
({{ route('roles.index') }})
4/#comment-
59)
/
@endcan
QCode (https://www.qcode.in/)
@can(‘view_users’)
All about Full Stack Web Development

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
{{trans(‘dashboard.user_management’)}}
({{ route('users.index') }})

Home (http://www.qcode.in) @endcan

In above html inner links are working


About (https://www.qcode.in/about/)
ne but how can i hide or show

Contact (https://www.qcode.in/contact/)
security on permission basis

Great tutorial, I have everything working until i get ‘This action is authorized’ for a
— ADEBOYE OLAITAN particular route which i have given permission to
MERCY
July 18, 2017
Am i missing something
(https://www.qcode.in/easy
-roles-and-permissions-in-
laravel-5-4/#comment-63)

When i open route like /patient/{patient},


— ADEBOYE OLAITAN Everything is ne
MERCY
But when i visit routes like
July 18, 2017
(https://www.qcode.in/easy /patient/{patient}/update,
-roles-and-permissions-in-
laravel-5-4/#comment-64)
If gives
‘This action is authorized’

Help please

Authorizable trait will work only if you follow the Laravel


— Saqueib resource controller, for example route for update should
July 18, 2017
(https://www.qcode
look like this
.in/easy-roles-and-
permissions-in-
laravel-5-
4/#comment-65) PUT|PATCH | /patient/{patient}
/
You can always use authorize('edit_patient') in your
QCode (https://www.qcode.in/)
controller methods if you don’t want to follow resourceful
All about Full Stack Webcontroller
Development
schema

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
Hi,
— for me route is ok but still give “This
Home (http://www.qcode.in)
Nabiullah
action is unauthorized.”
Khan
July 31, 2017
About (https://www.qcode.in/about/)
(https://www.
qcode.in/eas
y-roles-and-
Contact (https://www.qcode.in/contact/)
permissions-
in-laravel-5-
4/#comment-
77)

how to login as admin ?


— Suresh Prajapati
July 20, 2017
(https://www.qcode.in/easy
-roles-and-permissions-in- When you run php artisan db:seed on successful run it will
laravel-5-4/#comment-66)
— Mohd give you Admin email id, and default password is secret
Saqueib
July 20, 2017
(https://www.qcode
.in/easy-roles-and-
permissions-in-
laravel-5-
4/#comment-67)

When you run php artisan db:seed on successful run


— Saqueib it will give you Admin email id, and default password is
July 23, 2017
(https://www.qcode “secret”
.in/easy-roles-and-
permissions-in-
laravel-5-
4/#comment-68)

/
QCode (https://www.qcode.in/)
Hi. Great tutorial, I’m still working through it but encountered an issue. The check
— RichLove here: if ($exception instanceof AuthorizationException) in Handler.php is returning
All about FullJuly
Stack Web Development
27, 2017
(https://www.qcode.in/easy
false when there is an auth error. When I dump $exception it looks like an instance
Home
-roles-and-permissions-in- About
of AuthorizationException Contact
so not sure why the check return false. I noticed also this
(http://www.qcode.in)
laravel-5-4/#comment-69) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
line of code is commented out in the project github repo.

https://github.com/saqueib/roles-permissions-
Home (http://www.qcode.in)
laravel/blob/master/app/Exceptions/Handler.php#L48
(https://github.com/saqueib/roles-permissions-
About (https://www.qcode.in/about/)
laravel/blob/master/app/Exceptions/Handler.php#L48)

Contact (https://www.qcode.in/contact/)

My bad. Forgot to add ‘use


— RichLove IlluminateAuthAccessAuthorizationException;’
July 27, 2017
(https://www.qcode
.in/easy-roles-and-
permissions-in-
laravel-5-
it happens always, I bet you are using
4/#comment-70) — Saqueib sublime text, in PHPStorm you will get
July 27, 2017
(https://www.
instant hint if you forgot to import any
qcode.in/eas class.
y-roles-and-
permissions-
in-laravel-5-
4/#comment-
71) Ah, I am using
— SublimeText. I tried
RichLo
PHPStorm and liked it
ve
July 27, but need to invest a
2017
(https:// little time to get to
www.qc
know it better. I went
ode.in/e
asy- back to Sublime for
roles-
and-
simplicity (but less
permissi power maybe). Would
ons-in-
laravel- you recommend
5-
4/#com
switching to
ment- PHPStorm?
72)

— I think
Saq PHPStorm
ueib
is very
July
31, helpful, /
2017
you can
QCode (https://www.qcode.in/)
(http
see my s://w
ww.
All about Full Stack Web Development qcod
earlier
e.in/ post on
Home About easy Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
- this (https://www.qcode.in/contact/
roles
-
http://www.qcod
and- editor-use-
Home (http://www.qcode.in) per
miss web-
ions-
development/
in-
About (https://www.qcode.in/about/)
larav (http://www.qcod
el-5-
4/#c editor-use-
Contact (https://www.qcode.in/contact/)
om
web-
men
t-79) development/)

— Great,
Rich thanks.
Lov
Will read
e
July your article
31,
2017
(http
s://w
ww.
qcod
e.in/
easy
-
roles
-
and-
per
miss
ions-
in-
larav
el-5-
4/#c
om
men
t-80)

/
QCode (https://www.qcode.in/)
All about Full Stack Web Development
Fantastic tutorial and base ACL, thank you!
Home About Contact
— RichLove
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
July 27, 2017
(https://www.qcode.in/easy
-roles-and-permissions-in-
laravel-5-4/#comment-73)
Home (http://www.qcode.in)

About (https://www.qcode.in/about/)
Hi Sequeib,
— Nabiullah Khan Thanks for wonderful tutorial, please help me.
Contact (https://www.qcode.in/contact/)
July 30, 2017
(https://www.qcode.in/easy
-roles-and-permissions-in-
when I use “php artisan migrate” so it gives error
laravel-5-4/#comment-76)
[IlluminateDatabaseQueryException]

SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name ”


(SQL: create table “ (id int unsigned not null auto_increment primary key, `name`

varchar(191) not null, `guard_name` varchar(191) not null, `created_at` timestamp


null, `updated_at` timestamp null) default character set utf8mb4 collate
utf8mb4_un

icode_ci)

[PDOException]

SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name ”

Its seems you are not getting the table name from con g
— Saqueib le, please publish the vendor con g using this.
July 31, 2017
(https://www.qcode
.in/easy-roles-and-
php artisan vendor:publish --
permissions-in-
laravel-5- provider="SpatiePermissionPermissionServiceProvider"
4/#comment-78)
--tag="config"

Let me know how it goes.

/
QCode (https://www.qcode.in/)
I have successfully con gure the above example and worked ne for laravel
— somenet77 resource controller. But when i have added custom method in the controller the
All about Full Stack Web Development
August 10, 2017
(https://www.qcode.in/easy
403 error doesn’t work no protection over such url. But when i have added the such
Home
-roles-and-permissions-in- About
method in Contact
Abilities array in Authorizable traits it worked ne. But my question is, it
(http://www.qcode.in)
laravel-5-4/#comment-83) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
is not good to added every custom method in the Abilities array. So what is the
solution.

Home (http://www.qcode.in)

About (https://www.qcode.in/about/)
You don’t need to add in abilities array, that array is used
— Saqueib if you want to change naming convention of routes
August 11, 2017
Contact (https://www.qcode.in/contact/)
(https://www.qcode
altogether, by default its set for resource controller
.in/easy-roles-and- naming convention.
permissions-in-
laravel-5-
4/#comment-84) For any custom method authorization you should use

public function customeControllerAction() {

$this->authorize('your_custom_permission');

...

I hope this helps

Thanks now work ne. But still


— confuse in AuthorizationException
somenet77
Exception Handler when i have added
August 11,
2017 the code above you wrote in
(https://www.
qcode.in/eas Handler.php the permission doesn’t
y-roles-and-
work, every user has access all url
permissions-
in-laravel-5- although i doesn’t give the permission
4/#comment-
90) for those user. What is the problem ?

Its simple,
— AuthorizationException
Saquei
Handler checks if its an
b
Unauthorized
/
August
Exception it returns
QCode (https://www.qcode.in/)
12, 2017
redirect to home with
(https://
www.qc
All about Full Stack Web Development
ode.in/e
a ash mag, and if its
asy- an ajax call it will
Home roles- About Contact
(http://www.qcode.in)
and- (https://www.qcode.in/about/)
return unauthorize (https://www.qcode.in/contact/
permissi
ons-in-
msg as json. thats all
laravel- its doing
Home (http://www.qcode.in)
4/#com
5-

ment-
91)
About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)

(1/1) HttpException
— TZY This action is unauthorized.
August 11, 2017
(https://www.qcode.in/easy
-roles-and-permissions-in-
May i know how to solve this error?
laravel-5-4/#comment-85)
What should i do if i want user to be able to access the ACL?

You need to give user permissions to access that route,


— Mohd log in as admin and give permission. If you dont want ACL
Saqueib
on a certain controller just remove Authorizable trait from
August 11, 2017
(https://www.qcode controller and access will be allowed by default.
.in/easy-roles-and-
permissions-in-
laravel-5- If you need any other help let me know with some code
4/#comment-86)
where you are getting this unauthorized exception.

You need to give user permissions to access that route,


— Saqueib log in as admin and give permission. If you dont want ACL
August 11, 2017
(https://www.qcode
on a certain controller just remove Authorizable trait from
.in/easy-roles-and- controller and access will be allowed by default.
permissions-in-
laravel-5-
4/#comment-87)

/
If you need any other help let me know with some code
QCode (https://www.qcode.in/)
where you are getting this unauthorized exception.
All about Full Stack Web Development

Home About
Actually i am recovering a old project
Contact
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
— TZY that use laravel-permission package,
August 11,
2017
now i am able to access the role and
Home (http://www.qcode.in)
(https://www. user by commenting the Authorizable
qcode.in/eas
y-roles-and- trait. Even if i login as admin i am not
About (https://www.qcode.in/about/)
permissions-
able to make changes in the role and
in-laravel-5-
4/#comment- user view.
Contact (https://www.qcode.in/contact/)
88)

try clearing cache by


— running php artisan
Saquei
cache:forget
b
August spatie.permission.cache .
12, 2017
(https:// share some code so I
www.qc
can help you if
ode.in/e
asy- problem still exists.
roles-
and-
permissi
ons-in-
laravel-
5-
4/#com
ment-
92)

Hi there, when I run the php artisan db:seed, everything works normal till the:
— Ivan “Enter roles in comma separate format. [Admin,User]:”
August 11, 2017
(https://www.qcode.in/easy
-roles-and-permissions-in-
when I entered the roles, it show something like this:
laravel-5-4/#comment-89) [SymfonyComponentDebugExceptionFatalThrowableError]
Parse error: syntax error, unexpected ‘;’, expecting function (T_FUNCTION)

/
I rechecked the DatabaseSeeder.php and everything look ne, but maybe I miss
QCode (https://www.qcode.in/)
something
All about Full Stack Web Development
and btw, nice tutorial, and thank you.
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

I have a little problem


Home —
(http://www.qcode.in)
The Mistico
August 17, 2017 (1/1) HttpException
(https://www.qcode.in/easy
About (https://www.qcode.in/about/)
-roles-and-permissions-in-
This action is unauthorized.
laravel-5-4/#comment-93)
This happens when i open users view, i followed all this tutorial and i was
Contact (https://www.qcode.in/contact/)
comparing between your source code and mine, I can’t nd the solution.

https://github.com/Majunko/Test (https://github.com/Majunko/Test)

What can i do?

Thanks for sharing code, here is the issue, you have


— Saqueib translated the names of routes and they are not updated
August 17, 2017
(https://www.qcode
in view les. Change names in these les.
.in/easy-roles-and-
permissions-in-
laravel-5-
4/#comment-94) # routes/web.php

Route::resource('usuarios', 'UserController'); //

change users to usuarios

// update the route names in views


# resources/views/layouts/app.blade.php line:51-
57
@can('ver_usuarios')

Users
({{ route('usuarios.index') }})

@endcan

# resources/views/user/index.blade.php line:12,43
Create ({{ route('usuarios.create') }})

/
@include('shared._actions', [
QCode (https://www.qcode.in/)
'entity' => 'usuarios',
All about Full Stack Web'id'
Development
=> $item->id

])
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
This will show you the users list, but you will be needed to
update it everywhere, in Form action and in other views

Home (http://www.qcode.in)
also.

created a pull request, merge it on github to get the x.


About (https://www.qcode.in/about/)
I hope it helps, let me know how it goes
Contact (https://www.qcode.in/contact/)

Yeah it helps a lot, Thank you Saqueib


— The for taking your time for help me. Now
Mistico
everything goes very ne.
August 17,
2017
(https://www. Great tutorial, you’re amazing.
qcode.in/eas
y-roles-and- Regards.
permissions-
in-laravel-5-
4/#comment-
95)

Greetings from Colombia. I try to implement step by step this tutorial, but when I
— Pedro Araujo apply the command: “php artisan db:seed” I get the errors as imagen shows. Any
(http://www.ingpedroar
idea?
aujo.com)
August 28, 2017
(https://www.qcode.in/easy https://uploads.disquscdn.com/images/6a09b3193e4b28a99a0b3490f5519324aade44713
-roles-and-permissions-in-
(https://uploads.disquscdn.com/images/6a09b3193e4b28a99a0b3490f5519324aade4471
laravel-5-4/#comment-107)

add this on your DatabaseSeeder :


— Sanchez
August 28, 2017 use AppPermission;
(https://www.qcode
.in/easy-roles-and-
use AppRole;
permissions-in-
laravel-5-
4/#comment-109)
/
QCode (https://www.qcode.in/)
Thaxs, It helped. Have a nice day!
— Pedro
All about Full Stack Web Development
Araujo
(http://ww
Home w.ingpedroAbout Contact
(http://www.qcode.in)
araujo.com
(https://www.qcode.in/about/) (https://www.qcode.in/contact/
)
August 28,
2017
Home (http://www.qcode.in)
(https://www.
qcode.in/eas
y-roles-and-
About (https://www.qcode.in/about/)
permissions-
in-laravel-5-
4/#comment-
Contact (https://www.qcode.in/contact/)
110)

Hiiiii
— arun saw this is a very good tutorial
August 28, 2017
(https://www.qcode.in/easy
but i can’t undertood
-roles-and-permissions-in- where i add Authorizable Trait
laravel-5-4/#comment-108)
Please guide me.
Thanks

You should add on any resource controller you want to be


— Saqueib be authorized, you can create a resource controller using
August 29, 2017
(https://www.qcode
php artisan make:controller ProductController – r
.in/easy-roles-and-
permissions-in- Hope this helps
laravel-5-
4/#comment-111)

You can simply create le for trait under


— Sanchez App(Authorizable.php) just like the model.
August 29, 2017
(https://www.qcode
.in/easy-roles-and-
permissions-in-
laravel-5-
4/#comment-112)

/
QCode (https://www.qcode.in/)
All about Full Stack Web Development
Im trying to creat post, but i found error when i click save. any idea…what it causes?

Home — Sanchez About Contact


(http://www.qcode.in)
August 29, 2017 https://uploads.disquscdn.com/images/ba7224799b9ba1002e1ced234e074d716a7b1b54
(https://www.qcode.in/about/) (https://www.qcode.in/contact/
(https://www.qcode.in/easy
-roles-and-permissions-in-
(https://uploads.disquscdn.com/images/ba7224799b9ba1002e1ced234e074d716a7b1b54
laravel-5-4/#comment-113)

Home (http://www.qcode.in)

im creating new role for other user, but when i give access for editing and deleting
About (https://www.qcode.in/about/)
— Sanchez post in role
August 29, 2017
Contact (https://www.qcode.in/contact/)
https://uploads.disquscdn.com/images/ca9fa5241faf8d055d69a9fbdaed193053b6506a26
(https://www.qcode.in/easy
-roles-and-permissions-in- (https://uploads.disquscdn.com/images/ca9fa5241faf8d055d69a9fbdaed193053b6506a2
laravel-5-4/#comment-114)
, the action icon wont show. any idea what it cause?

please share the blade @can directive for this button in


— Saqueib your view, and make sure you have given user that role,
August 29, 2017
(https://www.qcode
also update user by editing it.
.in/easy-roles-and-
permissions-in-
laravel-5-
4/#comment-115) dunno why, but when i restart the
— Sanchez server….everything works ne :D….
August 29,
2017
thanks
(https://www.
qcode.in/eas
y-roles-and-
permissions- It could be the caching.
in-laravel-5-
4/#comment- — Glad it’s working
121) Saquei
b
August
29, 2017
(https://
www.qc
ode.in/e
asy-
roles-
and-
permissi
ons-in-
laravel-
5-
4/#com
ment-
122)

/
QCode (https://www.qcode.in/)
All about Full Stack Web Development

Home About Contact


(http://www.qcode.in)
Sanchez, i(https://www.qcode.in/about/)
getting this error, please help me (https://www.qcode.in/contact/
— dinesh
November 17, 2017
(https://www.qcode
Home (http://www.qcode.in)
.in/easy-roles-and-
permissions-in-
laravel-5-
About (https://www.qcode.in/about/)
4/#comment-209)

Contact (https://www.qcode.in/contact/)

Hi, I made extra column for the role table, called role_desc and it already work
— Ivan when I add new role with its description. It also already displayed at the Role page.
August 29, 2017
(https://www.qcode.in/easy
But, when I try to edit user, it gave an error, unde ned variable “role”. So my
-roles-and-permissions-in- question is, how to make it work at user edit page?
laravel-5-4/#comment-116)
for example, “Your Current role is Admin. (Role Description: …).
At _permissions.blade.php, I used “Role Description: {{ $role->role_desc }}” to show
role description.
Thank you.

Thats strange If you can, just create repo and push your
— Saqueib code I can see, must be something related to passing
August 29, 2017
(https://www.qcode
$role data to view
.in/easy-roles-and-
permissions-in-
laravel-5-
4/#comment-117) Thx for your time, the code exactly the
— Ivan same as the tutorial provided, I only
August 29,
2017
add the “Role Description: {{ $role-
(https://www. >role_desc }}” right above
qcode.in/eas
y-roles-and- “@foreach($permissions as $perm)”at
permissions-
in-laravel-5-
_permissions.blade.php ( rst image)
4/#comment- and the second image for the
118)
RoleController which I change at little
at store method.
https://uploads.disquscdn.com/images/4bc37

/
(https://uploads.disquscdn.com/images/4bc3
QCode (https://www.qcode.in/)
https://uploads.disquscdn.com/images/a1390
All about Full Stack Web Development
(https://uploads.disquscdn.com/images/a139

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
I see, you have called
— the $role variable
Saquei
Home (http://www.qcode.in) before its initialized, if
b
August you see on line 17 i am
About (https://www.qcode.in/about/)
29, 2017
checking if $role is set
(https://
www.qc
before doing anything
Contact (https://www.qcode.in/contact/)
ode.in/e
asy- with it.
roles-
and-
permissi
You can either more
ons-in- Role Description in
laravel-
5- side Line 17 if block or
4/#com
just check isset($role)
ment-
119) before calling $role-
>role_desc.

One side note I have


used same
_permissions.blade.php

partial in user edit and


role edit, thats why i
needed to check if
$role is set.

— I got it
Ivan now, thx
Aug
ust for your
29,
time.
2017
(http
s://w
ww.
qcod
e.in/
easy
-
roles
-
and-
per
miss
/
ions-

QCode (https://www.qcode.in/)
in-
larav
el-5-
All about Full Stack Web Development
4/#c
om
Home About
men Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
t- (https://www.qcode.in/contact/
120)

Home (http://www.qcode.in)

About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)

When using custom guard like admin. And put the Authorizable trait in controller it
— somenet77 doesn’t work. i get 403 exception, how to x this one.
August 30, 2017
(https://www.qcode.in/easy
-roles-and-permissions-in-
laravel-5-4/#comment-123)
you should try to set your guard default if possible
— Saqueib (config('auth.default.guard') or you can check this
August 31, 2017
(https://www.qcode to see how you can use multiple guards
.in/easy-roles-and-
https://github.com/spatie/laravel-permission#using-
permissions-in-
laravel-5- multiple-guards (https://github.com/spatie/laravel-
4/#comment-124)
permission#using-multiple-guards)

hi Saqueib i used default guard for


— front login and my role base login is
somenet77
backend so how to x for backend. if i
August 31,
2017 have change default guard to admin in
(https://www.
qcode.in/eas auth.php con g le its work, but i
y-roles-and-
don’t want to change default one.
permissions-
in-laravel-5-
4/#comment-
125)
@somenet77:disqus i
— Irfan have same issue. are
Abdurr
You has resolve?
asyid
January
3, 2018
(https://
www.qc
/
ode.in/e

QCode (https://www.qcode.in/)
asy-
roles-
and-
All about Full Stack Web Development permissi
ons-in-
Home About laravel- Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
5- (https://www.qcode.in/contact/
4/#com
ment-
233)

Home (http://www.qcode.in)

About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)

Hi,
— Colin Stewart Thanks for a great tutorial.
September 6, 2017
(https://www.qcode.in/easy
When I run the command “php artisan db:seed” I get this error:
-roles-and-permissions-in- [InvalidArgumentException]
laravel-5-4/#comment-130)
Unable to locate factory with name [default] [AppPost].
Any idea why?

Either you forgot to de ne a factory for AppPost model


— Saqueib or you haven’t imported it at the top of DatabaseSeeder .
September 6, 2017
(https://www.qcode Share you database/seeds/DatabaseSeeder.php on
.in/easy-roles-and-
https://pastebin.com/ (https://pastebin.com/) le if
permissions-in-
laravel-5- problem exists.
4/#comment-131)

I forgot to de ne a factory for AppPost


— Colin model, it’s all working ne now.
Stewart
Thanks for your reply.
September 6,
2017
(https://www.
qcode.in/eas
y-roles-and- How you x it? Tanks
permissions-

in-laravel-5-
4/#comment- Cleber
132) Martins
October
25, 2017
(https://
www.qc
ode.in/e /
asy-

QCode (https://www.qcode.in/)
roles-
and-
permissi
All about Full Stack Web Development
ons-in-
laravel-
Home 5- About Contact
(http://www.qcode.in)
4/#com (https://www.qcode.in/about/) (https://www.qcode.in/contact/
ment-
184)

Home (http://www.qcode.in)

About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)
How de ne a factory?
— Cleber
Martins
October 25,
2017
(https://www.
qcode.in/eas
y-roles-and-
permissions-
in-laravel-5-
4/#comment-
183)

Hi,
— Colin Stewart I don’t get the ash messages appearing when I do something, like ash(‘Role
September 7, 2017
(https://www.qcode.in/easy
Added’);
-roles-and-permissions-in- What am I missing?
laravel-5-4/#comment-133)

Check your layout le, it must include the


— Saqueib @include('flash::message') view partial.
September 7, 2017
(https://www.qcode
.in/easy-roles-and-
permissions-in-
laravel-5-
4/#comment-134)
@include('flash::message')

/
Also include the JS part to show it
QCode (https://www.qcode.in/)
All about Full Stack Web Development

Home About
$(function () { Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
// flash auto hide
(https://www.qcode.in/contact/
$('#flash-msg .alert').not('.alert-danger,
.alert-important').delay(6000).slideUp(500);
Home (http://www.qcode.in)
})

About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)
Check here for layout https://github.com/saqueib/roles-
permissions-
laravel/blob/master/resources/views/layouts/app.blade.php#L114
(https://github.com/saqueib/roles-permissions-
laravel/blob/master/resources/views/layouts/app.blade.php#L114

Many thanks.
— Colin
Stewart
September 7,
2017
(https://www.
qcode.in/eas
y-roles-and-
permissions-
in-laravel-5-
4/#comment-
135)

Hi again,
— Colin Stewart If I visit an invalid URL like /users/10/edit (when user 10 does not exist), I get the
September 7, 2017
(https://www.qcode.in/easy
attached error rather than the exception handling, any ideas?
-roles-and-permissions-in- https://uploads.disquscdn.com/images/f785476fa84612935ce34a760a302ec1b611fcf6a7
laravel-5-4/#comment-136)
(https://uploads.disquscdn.com/images/f785476fa84612935ce34a760a302ec1b611fcf6a7

/
— Saqueib

QCode (https://www.qcode.in/)
Maybe your logged in user dont have permission to edit a
September 8, 2017
(https://www.qcode
.in/easy-roles-and- user, also you should change UserController@edit to
All about Full Stack Web Development
permissions-in-
use User::findOrFail($id) instead $user =
laravel-5-
Home 4/#comment-137) About which will give 404 if user doesn’t Contact
User::find($id);
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
exists, https://github.com/saqueib/roles-permissions-
laravel/blob/master/app/Http/Controllers/UserController.php#L9

Home (http://www.qcode.in)
(https://github.com/saqueib/roles-permissions-
laravel/blob/master/app/Http/Controllers/UserController.php#L9
About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)
I have the code included you speci ed
— Colin and the user can edit users.
Stewart
If the user has permissions to edit a
September 8,
2017 user and I say edit user 3, the user
(https://www.
qcode.in/eas account edit appears. If I then change
y-roles-and-
the URL in the browser to a user that
permissions-
in-laravel-5- doesn’t exist (like user 31) then I get
4/#comment-
138) an error saying:
Trying to get property of non-object
(View:
/resources/views/user/edit.blade.php),
shouldn’t that get caught by the
exception handler?

This is really cool!


— Ayman Ishimwe
September 11, 2017
(https://www.qcode.in/easy
-roles-and-permissions-in-
laravel-5-4/#comment-139)

I have bumped into an issue, after adding other permissions manually, i couldn’t
— Ayman Ishimwe manage to make them also default to the Admin role, and it also seems like i can’t
September 11, 2017
(https://www.qcode.in/easy
check(tick) them. Can someone help me out!

/
-roles-and-permissions-in-
Regards!
QCode (https://www.qcode.in/)
laravel-5-4/#comment-140)

All about Full Stack Web Development


It seems cache issue, run php artisan cache:forget
Home — Saqueib About Contact
spatie.permission.cache it should x it
(http://www.qcode.in)
September 14,
(https://www.qcode.in/about/) (https://www.qcode.in/contact/
2017
(https://www.qcode
.in/easy-roles-and-
Home permissions-in-
(http://www.qcode.in)
laravel-5-
4/#comment-141)
About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)

Hi, Great post. but while i am using


— Gunjan php artisan vendor:publish –
September 15, 2017
(https://www.qcode.in/easy
provider=”SpatiePermissionPermissionServiceProvider” –tag=”migrations”
-roles-and-permissions-in-
laravel-5-4/#comment-142) this command its showing me an exception

PHP Fatal error: Class ‘SpatiePermissionPermissionServiceProvider’ not found in


C:rplvendorlaravelframeworksrcIlluminateFoundationProviderRepository.php on
line 208
[SymfonyComponentDebugExceptionFatalErrorException]
Class ‘SpatiePermissionPermissionServiceProvider’ not found

Kindly help me out. Thanks in advance

As it says, you need to install add


— Saqueib SpatiePermissionPermissionServiceProvider::class,
September 15,
2017
In con g/app.php providers array, currently laravel is not
(https://www.qcode able to nd this provider binding
.in/easy-roles-and-
permissions-in-
laravel-5-
4/#comment-143)
Thanks for your time.
— Gunjan kindly check my code. and help me
September
15, 2017
(https://www.
env(‘APP_NAME’, ‘Laravel’),
qcode.in/eas
y-roles-and- /*
permissions-
in-laravel-5- |
4/#comment-
—————————————————————
144)
/
| Application Environment
QCode (https://www.qcode.in/)
|
All about Full Stack Web Development
—————————————————————
|
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
| This value determines the (https://www.qcode.in/contact/
“environment” your application is
currently
Home (http://www.qcode.in)| running in. This may determine how
you prefer to con gure various
About (https://www.qcode.in/about/)
| services your application utilizes. Set
this in your “.env” le.
Contact (https://www.qcode.in/contact/)
|
*/

‘env’ => env(‘APP_ENV’, ‘production’),

/*
|
—————————————————————
| Application Debug Mode
|
—————————————————————
|
| When your application is in debug
mode, detailed error messages with
| stack traces will be shown on every
error that occurs within your
| application. If disabled, a simple
generic error page is shown.
|
*/

‘debug’ => env(‘APP_DEBUG’, false),

/*
|
—————————————————————
| Application URL
|
—————————————————————
|
/
| This URL is used by the console to
QCode (https://www.qcode.in/)
properly generate URLs when using
All about Full Stack Web Development
| the Artisan command line tool. You
should set this to the root of
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
| your application so that it is used (https://www.qcode.in/contact/
when running Artisan tasks.
|
Home (http://www.qcode.in)*/

About (https://www.qcode.in/about/)
‘url’ => env(‘APP_URL’,
‘http://localhost’),
Contact (https://www.qcode.in/contact/)
/*
|
—————————————————————
| Application Timezone
|
—————————————————————
|
| Here you may specify the default
timezone for your application, which
| will be used by the PHP date and
date-time functions. We have gone
| ahead and set this to a sensible
default for you out of the box.
|
*/

‘timezone’ => ‘UTC’,

/*
|
—————————————————————
| Application Locale Con guration
|
—————————————————————
|
| The application locale determines
the default locale that will be used
| by the translation service provider.
You are free to set this value
/
| to any of the locales which will be
QCode (https://www.qcode.in/)
supported by the application.
All about Full Stack Web Development
|
*/
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
‘locale’ => ‘en’,

/*
Home (http://www.qcode.in)
|
—————————————————————
About (https://www.qcode.in/about/)
| Application Fallback Locale
|
Contact (https://www.qcode.in/contact/)
—————————————————————
|
| The fallback locale determines the
locale to use when the current one
| is not available. You may change the
value to correspond to any of
| the language folders that are
provided through your application.
|
*/

‘fallback_locale’ => ‘en’,

/*
|
—————————————————————
| Encryption Key
|
—————————————————————
|
| This key is used by the Illuminate
encrypter service and should be set
| to a random, 32 character string,
otherwise these encrypted strings
| will not be safe. Please do this
before deploying an application!
|
*/

/
‘key’ => env(‘APP_KEY’),
QCode (https://www.qcode.in/)
‘cipher’ => ‘AES-256-CBC’,
All about Full Stack Web Development

/*
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
| (https://www.qcode.in/contact/
—————————————————————
| Logging Con guration
Home (http://www.qcode.in)
|
—————————————————————
About (https://www.qcode.in/about/)
|
| Here you may con gure the log
Contact (https://www.qcode.in/contact/)
settings for your application. Out of
| the box, Laravel uses the Monolog
PHP logging library. This gives
| you a variety of powerful log
handlers / formatters to utilize.
|
| Available Settings: “single”, “daily”,
“syslog”, “errorlog”
|
*/

‘log’ => env(‘APP_LOG’, ‘single’),

‘log_level’ => env(‘APP_LOG_LEVEL’,


‘debug’),

/*
|
—————————————————————
| Autoloaded Service Providers
|
—————————————————————
|
| The service providers listed here will
be automatically loaded on the
| request to your application. Feel free
to add your own services to
| this array to grant expanded

/
functionality to your applications.
QCode (https://www.qcode.in/)
|
All about Full Stack Web Development
*/

Home About
‘providers’ => [ Contact
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
/*
* Laravel Framework Service
Home (http://www.qcode.in)
Providers…
*/
About (https://www.qcode.in/about/)
IlluminateAuthAuthServiceProvider::class,
IlluminateBroadcastingBroadcastServiceProv
Contact (https://www.qcode.in/contact/)
IlluminateBusBusServiceProvider::class,
IlluminateCacheCacheServiceProvider::class,
IlluminateFoundationProvidersConsoleSuppo
IlluminateCookieCookieServiceProvider::class
IlluminateDatabaseDatabaseServiceProvider:
IlluminateEncryptionEncryptionServiceProvid
IlluminateFilesystemFilesystemServiceProvide
IlluminateFoundationProvidersFoundationSe
IlluminateHashingHashServiceProvider::class
IlluminateMailMailServiceProvider::class,
IlluminateNoti cationsNoti cationServicePro
IlluminatePaginationPaginationServiceProvid
IlluminatePipelinePipelineServiceProvider::cla
IlluminateQueueQueueServiceProvider::class
IlluminateRedisRedisServiceProvider::class,
IlluminateAuthPasswordsPasswordResetServ
IlluminateSessionSessionServiceProvider::clas
IlluminateTranslationTranslationServiceProvi
IlluminateValidationValidationServiceProvide
IlluminateViewViewServiceProvider::class,
SpatiePermissionPermissionServiceProvider::
LaracastsFlashFlashServiceProvider::class,
CollectiveHtmlHtmlServiceProvider::class,

/*
* Package Service Providers…
*/
LaravelTinkerTinkerServiceProvider::class,
/
/*
QCode (https://www.qcode.in/)
* Application Service Providers…
All about Full Stack Web Development
*/
AppProvidersAppServiceProvider::class,
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
AppProvidersAuthServiceProvider::class, (https://www.qcode.in/contact/
//
AppProvidersBroadcastServiceProvider::class
Home (http://www.qcode.in)AppProvidersEventServiceProvider::class,
AppProvidersRouteServiceProvider::class,
About (https://www.qcode.in/about/)
],
Contact (https://www.qcode.in/contact/)
/*
|
—————————————————————
| Class Aliases
|
—————————————————————
|
| This array of class aliases will be
registered when this application
| is started. However, feel free to
register as many as you wish as
| the aliases are “lazy” loaded so they
don’t hinder performance.
|
*/

‘aliases’ => [

‘App’ =>
IlluminateSupportFacadesApp::class,
‘Artisan’ =>
IlluminateSupportFacadesArtisan::class,
‘Auth’ =>
IlluminateSupportFacadesAuth::class,
‘Blade’ =>
IlluminateSupportFacadesBlade::class,
‘Broadcast’ =>
IlluminateSupportFacadesBroadcast::class,
‘Bus’ =>
/
IlluminateSupportFacadesBus::class,
QCode (https://www.qcode.in/)
‘Cache’ =>
All about Full Stack Web Development
IlluminateSupportFacadesCache::class,
‘Con g’ =>
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
IlluminateSupportFacadesCon g::class, (https://www.qcode.in/contact/
‘Cookie’ =>
IlluminateSupportFacadesCookie::class,
Home (http://www.qcode.in)‘Crypt’ =>
IlluminateSupportFacadesCrypt::class,
About (https://www.qcode.in/about/)
‘DB’ =>
IlluminateSupportFacadesDB::class,
Contact (https://www.qcode.in/contact/)
‘Eloquent’ =>
IlluminateDatabaseEloquentModel::class,
‘Event’ =>
IlluminateSupportFacadesEvent::class,
‘File’ =>
IlluminateSupportFacadesFile::class,
‘Gate’ =>
IlluminateSupportFacadesGate::class,
‘Hash’ =>
IlluminateSupportFacadesHash::class,
‘Lang’ =>
IlluminateSupportFacadesLang::class,
‘Log’ =>
IlluminateSupportFacadesLog::class,
‘Mail’ =>
IlluminateSupportFacadesMail::class,
‘Noti cation’ =>
IlluminateSupportFacadesNoti cation::class,
‘Password’ =>
IlluminateSupportFacadesPassword::class,
‘Queue’ =>
IlluminateSupportFacadesQueue::class,
‘Redirect’ =>
IlluminateSupportFacadesRedirect::class,
‘Redis’ =>
IlluminateSupportFacadesRedis::class,
‘Request’ =>
IlluminateSupportFacadesRequest::class,
/
‘Response’ =>
QCode (https://www.qcode.in/)
IlluminateSupportFacadesResponse::class,
All about Full Stack Web Development
‘Route’ =>
IlluminateSupportFacadesRoute::class,
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
‘Schema’ => (https://www.qcode.in/contact/
IlluminateSupportFacadesSchema::class,
‘Session’ =>
Home (http://www.qcode.in)IlluminateSupportFacadesSession::class,
‘Storage’ =>
About (https://www.qcode.in/about/)
IlluminateSupportFacadesStorage::class,
‘URL’ =>
Contact (https://www.qcode.in/contact/)
IlluminateSupportFacadesURL::class,
‘Validator’ =>
IlluminateSupportFacadesValidator::class,
‘View’ =>
IlluminateSupportFacadesView::class,
‘Form’ =>
CollectiveHtmlFormFacade::class,
‘Html’ =>
CollectiveHtmlHtmlFacade::class,

],

];

share your
— composer.json le
Saquei
b
Septem
ber 15,
— Thanks for
2017
(https:// Gun reply.
www.qc jan
ode.in/e kindly
Sept
asy- emb check
roles- er
and- 15, composser.json
permissi 2017
ons-in-
{
(http
laravel- s://w “name”:
5- ww.
4/#com qcod “laravel/laravel”,
ment- e.in/
146)
“description”:
easy
- “The
roles
/
-
Laravel
QCode (https://www.qcode.in/)
and-
Framework.”, per
miss
All about Full Stack Web Developmentions- “keywords”:
in- [“framework”,
Home Aboutlarav Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
el-5- “laravel”], (https://www.qcode.in/contact/
4/#c
om
“license”:
men “MIT”,
Home (http://www.qcode.in) t-
148) “type”:
“project”,
About (https://www.qcode.in/about/)
“require”: {
“php”:
Contact (https://www.qcode.in/contact/)
“>=5.6.4”,
“laravel/framewo
“5.4.*”,
“laravel/tinker”:
“~1.0”,
“spatie/laravel-
permission”:
“^2.1”,
“laracasts/ ash”:
“^3.0”,
“laravelcollective/
“^5.3.0”,
},
“require-
dev”: {
“fzaninotto/faker
“~1.4”,
“mockery/mocke
“0.9.*”,
“phpunit/phpunit
“~5.7”
},
“autoload”:
{
“classmap”:
[
“database”
],
/
“psr-4”: {
QCode (https://www.qcode.in/)
“App\”:
All about Full Stack Web Development “app/”
}
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
}, (https://www.qcode.in/contact/
“autoload-
dev”: {
Home (http://www.qcode.in) “psr-4”: {
“Tests\”:
About (https://www.qcode.in/about/)
“tests/”
}
Contact (https://www.qcode.in/contact/)
},
“scripts”: {
“post-root-
package-
install”: [
“php -r
“ le_exists(‘.env’)
||
copy(‘.env.examp
‘.env’);””
],
“post-
create-
project-
cmd”: [
“php
artisan
key:generate”
],
“post-
install-
cmd”: [
“Illuminate\Foun
“php
artisan
optimize”
],
“post-
/
update-
QCode (https://www.qcode.in/)
cmd”: [
All about Full Stack Web Development “Illuminate\Foun
“php
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
artisan (https://www.qcode.in/contact/
optimize”
]
Home (http://www.qcode.in) },
“con g”: {
About (https://www.qcode.in/about/)
“preferred-
install”:
Contact (https://www.qcode.in/contact/)
“dist”,
“sort-
packages”:
true,
“optimize-
autoloader”:
true
}
}

— run
San composer
tut
update
Ken
dur
Dece
mbe
r 7,
2017
(http
s://w
ww.
qcod
e.in/
easy
-
roles
-
and-
per
miss
ions-
in-
larav
/
el-5-

QCode (https://www.qcode.in/)
4/#c
om
men
All about Full Stack Web Development
t-
213)
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Home (http://www.qcode.in)

About (https://www.qcode.in/about/)

‘providers’ => [
Contact (https://www.qcode.in/contact/)
— Gunjan
September /*
15, 2017
(https://www.
* Laravel Framework Service
qcode.in/eas Providers…
y-roles-and-
permissions- */
in-laravel-5-
IlluminateAuthAuthServiceProvider::class,
4/#comment-
145) IlluminateBroadcastingBroadcastServiceProv
IlluminateBusBusServiceProvider::class,
IlluminateCacheCacheServiceProvider::class,
IlluminateFoundationProvidersConsoleSuppo
IlluminateCookieCookieServiceProvider::class
IlluminateDatabaseDatabaseServiceProvider:
IlluminateEncryptionEncryptionServiceProvid
IlluminateFilesystemFilesystemServiceProvide
IlluminateFoundationProvidersFoundationSe
IlluminateHashingHashServiceProvider::class
IlluminateMailMailServiceProvider::class,
IlluminateNoti cationsNoti cationServicePro
IlluminatePaginationPaginationServiceProvid
IlluminatePipelinePipelineServiceProvider::cla
IlluminateQueueQueueServiceProvider::class
IlluminateRedisRedisServiceProvider::class,
IlluminateAuthPasswordsPasswordResetServ
IlluminateSessionSessionServiceProvider::clas
IlluminateTranslationTranslationServiceProvid
IlluminateValidationValidationServiceProvide
IlluminateViewViewServiceProvider::class,

/
SpatiePermissionPermissionServiceProvider::
QCode (https://www.qcode.in/)
LaracastsFlashFlashServiceProvider::class,
All about Full Stack Web CollectiveHtmlHtmlServiceProvider::class,
Development

Home /* About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
* Package Service Providers…
*/

Home (http://www.qcode.in)
LaravelTinkerTinkerServiceProvider::class,

/*
About (https://www.qcode.in/about/)
* Application Service Providers…
*/
Contact (https://www.qcode.in/contact/)
AppProvidersAppServiceProvider::class,
AppProvidersAuthServiceProvider::class,
//
AppProvidersBroadcastServiceProvider::class
AppProvidersEventServiceProvider::class,
AppProvidersRouteServiceProvider::class,

],

/*
|
—————————————————————
| Class Aliases
|
—————————————————————
|
| This array of class aliases will be
registered when this application
| is started. However, feel free to
register as many as you wish as
| the aliases are “lazy” loaded so they
don’t hinder performance.
|
*/

‘aliases’ => [

‘App’ =>
IlluminateSupportFacadesApp::class,
‘Artisan’ =>
/
IlluminateSupportFacadesArtisan::class,
QCode (https://www.qcode.in/)
‘Auth’ =>
All about Full Stack Web IlluminateSupportFacadesAuth::class,
Development
‘Blade’ =>
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
IlluminateSupportFacadesBlade::class, (https://www.qcode.in/contact/
‘Broadcast’ =>
IlluminateSupportFacadesBroadcast::class,
Home (http://www.qcode.in)
‘Bus’ =>
IlluminateSupportFacadesBus::class,
About (https://www.qcode.in/about/)
‘Cache’ =>
IlluminateSupportFacadesCache::class,
Contact (https://www.qcode.in/contact/)
‘Con g’ =>
IlluminateSupportFacadesCon g::class,
‘Cookie’ =>
IlluminateSupportFacadesCookie::class,
‘Crypt’ =>
IlluminateSupportFacadesCrypt::class,
‘DB’ =>
IlluminateSupportFacadesDB::class,
‘Eloquent’ =>
IlluminateDatabaseEloquentModel::class,
‘Event’ =>
IlluminateSupportFacadesEvent::class,
‘File’ =>
IlluminateSupportFacadesFile::class,
‘Gate’ =>
IlluminateSupportFacadesGate::class,
‘Hash’ =>
IlluminateSupportFacadesHash::class,
‘Lang’ =>
IlluminateSupportFacadesLang::class,
‘Log’ =>
IlluminateSupportFacadesLog::class,
‘Mail’ =>
IlluminateSupportFacadesMail::class,
‘Noti cation’ =>
IlluminateSupportFacadesNoti cation::class,
‘Password’ =>
IlluminateSupportFacadesPassword::class,
/
‘Queue’ =>
QCode (https://www.qcode.in/)
IlluminateSupportFacadesQueue::class,
All about Full Stack Web ‘Redirect’
Development
=>
IlluminateSupportFacadesRedirect::class,
Home About Contact
(http://www.qcode.in)
‘Redis’ => (https://www.qcode.in/about/) (https://www.qcode.in/contact/
IlluminateSupportFacadesRedis::class,
‘Request’ =>
Home (http://www.qcode.in)
IlluminateSupportFacadesRequest::class,
‘Response’ =>
About (https://www.qcode.in/about/)
IlluminateSupportFacadesResponse::class,
‘Route’ =>
Contact (https://www.qcode.in/contact/)
IlluminateSupportFacadesRoute::class,
‘Schema’ =>
IlluminateSupportFacadesSchema::class,
‘Session’ =>
IlluminateSupportFacadesSession::class,
‘Storage’ =>
IlluminateSupportFacadesStorage::class,
‘URL’ =>
IlluminateSupportFacadesURL::class,
‘Validator’ =>
IlluminateSupportFacadesValidator::class,
‘View’ =>
IlluminateSupportFacadesView::class,
‘Form’ =>
CollectiveHtmlFormFacade::class,
‘Html’ =>
CollectiveHtmlHtmlFacade::class,

],

];

— Samuel
/
September 16, 2017

QCode (https://www.qcode.in/)
(https://www.qcode.in/easy
Thanks for this write up, you saved me many hours of work. I’m having a little
-roles-and-permissions-in-
laravel-5-4/#comment-150) problem with the Authorizable Trait tho. right now, when I try to access a controller
All about Full Stack Web Development
that uses the trait (let’s say ExampleController), I get “Unde ned method “…
Home About
Controllers\ExampleController::authorize”. Contact
Please kindly support.
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Thats strange, make sure you ExampleController


Home (http://www.qcode.in)
— Saqueib extends base AppHttpControllersController.php
September 16,
About (https://www.qcode.in/about/)
2017
(https://www.qcode
.in/easy-roles-and-
class ExampleController extends Controller {
Contact (https://www.qcode.in/contact/)
permissions-in-
laravel-5- ...
4/#comment-151)
}

Since authorize() method comes from

AuthorizesRequests trait.

Let me know how it goes.

Thank you for the quick reply. You are


— Samuel right, I wasn’t extending my base
September
16, 2017
controller, so I couldn’t access the
(https://www. AuthorizesRequests trait. that’s xed.
qcode.in/eas
y-roles-and- thank you. 🙂
permissions-
in-laravel-5-
4/#comment-
153)

Sir, do you have a tutorial base on native laravel auth? Can you make it multiple role
— Junie Negentien permission using the native way? Packages has its own disadvantages I’m looking
October 3, 2017
(https://www.qcode.in/easy
into some native way. There are some but it doesn’t t on what Im looking for. Btw,
-roles-and-permissions-in- you have the better explaination based on spatie . Thanks for this
laravel-5-4/#comment-173)

/
— Lambert

QCode (https://www.qcode.in/)
Great tutorials. Wouldn’t it be better to use a middleware ? You would expect to
October 27, 2017
(https://www.qcode.in/easy
receive a 403 but if the data doesn’t passe validation you will get a 422 instead. I
All -roles-and-permissions-in-
about Full Stack Web Development
laravel-5-4/#comment-185)
made a quick gist based on your code.
Home About
https://gist.github.com/lamberttraccard/c0ab9c1 Contact
7b52bd4eb9d8fa188c4470c
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
(https://gist.github.com/lamberttraccard/c0ab9c1 7b52bd4eb9d8fa188c4470c)

Home (http://www.qcode.in)
Thats great idea, there is always more than one way to

About (https://www.qcode.in/about/)
— Saqueib solve a problem. Thanks for sharing your gist
October 27, 2017
(https://www.qcode

Contact (https://www.qcode.in/contact/)
.in/easy-roles-and-
permissions-in-
laravel-5-
4/#comment-186)

Hi,
— Ajaxiome One thing i can’t understand is in the Trait Authorizable
October 31, 2017
(https://www.qcode.in/easy
when we call $this->authorize($ability);
-roles-and-permissions-in- then we call the Laravel’s permission,and not the spatie one’s
laravel-5-4/#comment-187)
Then for every route i get an Unauthorized Exception, because the $ability is
unknow from Laravel core, just known by Spatie’s Tables

I would imagine in the trait a call to a Spatie Authorize method.

Do you know how it works ?

Thx

If i run php artisan auth:permission appear


— Fahreza Armando [SymfonyComponentConsoleExceptionRuntimeException]
Drakel
Not enough arguments (missing: “name”).
November 1, 2017
(https://www.qcode.in/easy
-roles-and-permissions-in- How to x? Thank You
laravel-5-4/#comment-188)

Its strange, please try with other name also php artisan
— Saqueib auth:permission appears
November 2, 2017
(https://www.qcode You can seed the data which will create admin user. php
.in/easy-roles-and- /
permissions-in-
artisan db:seed
QCode (https://www.qcode.in/)
laravel-5-
4/#comment-189)

All about Full Stack Web Development

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
Thank yo for the article. Great stu .
— nikalai Quick question… where should I change the migration le to accomodate UUID for
HomeNovember
(http://www.qcode.in)
2, 2017
(https://www.qcode.in/easy
the user_id? In my users table, the users have UUID..
-roles-and-permissions-in-
About (https://www.qcode.in/about/)
laravel-5-4/#comment-190)

thanks nikalai, you can update migration to add any eld


Contact (https://www.qcode.in/contact/)
— Saqueib on users migration
November 2, 2017
(https://www.qcode
.in/easy-roles-and-
https://github.com/saqueib/roles-permissions-
permissions-in- laravel/blob/master/database/migrations/2014_10_12_000000_cr
laravel-5-
4/#comment-191) (https://github.com/saqueib/roles-permissions-
laravel/blob/master/database/migrations/2014_10_12_000000_cr

you should also match it in the model factory


https://github.com/saqueib/roles-permissions-
laravel/blob/master/database/factories/ModelFactory.php#L22
(https://github.com/saqueib/roles-permissions-
laravel/blob/master/database/factories/ModelFactory.php#L22)

Thanks for the quick reply.


— nikalai In my User model I have:
November 2,
2017
(https://www.
// Do not use auto-incrementing
qcode.in/eas public $incrementing = false;
y-roles-and-
permissions-
in-laravel-5- and in the migration, I have the eld
4/#comment-
set to UUID.
192)

But when I run php artisan


migrate:refresh –seed, I get the
following error:

[IlluminateDatabaseQueryException]

/
SQLSTATE[22P02]: Invalid text
QCode (https://www.qcode.in/)
representation: 7 ERROR: invalid input
All about Full Stack Web Development syntax for integer: “b2038760-bf9e-
11e7-a022-6b5e6a138514” (SQL: insert
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
into “model_has_roles” (“model_id”,(https://www.qcode.in/contact/
“model_type

Home (http://www.qcode.in) “, “role_id”) values (b2038760-bf9e-


11e7-a022-6b5e6a138514, AppUser,

About (https://www.qcode.in/about/)
1))

Is it something I should o in the


Contact (https://www.qcode.in/contact/)
create_permission_tables.php
migration?

[PDOException]

SQLSTATE[22P02]: Invalid text


representation: 7 ERROR: invalid input
syntax for integer: “b2038760-bf9e-
11e7-a022-6b5e6a138514”

oh I see, in this case


— you will need to
Saquei
change the migration
b
Novemb for
er 2,
2017 CreatePermissionTables,
(https://
out of the box it setup
www.qc
ode.in/e to use int, tweak all the
asy-
roles-
reference to use uuid
and- instead of integer
permissi
ons-in- column.
laravel-
5-
4/#com
ment-
193) — I’ve
nika replaced
lai
all the
Nov
emb integer
er 3,
2017 with UUID.
(http
Nor I run
s://w
/
ww.
into a
QCode (https://www.qcode.in/)
qcod
di erent e.in/
easy
All about Full Stack Web Development -
error:
roles
Home About - [IlluminateDatab Contact
(http://www.qcode.in) (https://www.qcode.in/about/)
and- (https://www.qcode.in/contact/
per
miss SQLSTATE[42830
ions-
Invalid
Home (http://www.qcode.in) in-
larav foreign
el-5-
4/#c key: 7
About (https://www.qcode.in/about/)
om
ERROR:
men
there is no
t-
Contact (https://www.qcode.in/contact/)
194)
unique
constraint
matching
given keys
for
referenced
table
“permissions”
(SQL: alter
table
“model_has_perm
add
constraint

“model_has_perm
foreign key
(“permission_id”)
references
“permissions”
(“id”) on
delete
cascade)

/
QCode (https://www.qcode.in/)
All about Full Stack Web Development
Amazing tutorial, I have some problems though. First, when a user is not authorized
Home — zietbukuel to see access
Abouta resource, I get this error: Contact
(http://www.qcode.in)
November 6, 2017 (https://www.qcode.in/about/) (https://www.qcode.in/contact/
(https://www.qcode.in/easy
-roles-and-permissions-in-
Symfony Component HttpKernel Exception AccessDeniedHttpException
laravel-5-4/#comment-195) This action is unauthorized.
Home (http://www.qcode.in)
It seems that the Exception handler isn’t doing anything at all, I should be
About (https://www.qcode.in/about/)
redirected with a ash message, right?

Second issue is that when I try to create a new user, I get this error:
Contact (https://www.qcode.in/contact/)
Symfony Component HttpKernel Exception MethodNotAllowedHttpException
No message

This happens when I hit the submit button.

Please let me know if you want me to share my code with you. Thanks a lot.

Hi, this is bug?


— Yudi Purwanto
November 6, 2017 I have allow user for delete_users and record found in table role_has_permissions
(https://www.qcode.in/easy
-roles-and-permissions-in-
then in le user/index.blade.php edited like this
laravel-5-4/#comment-196)

@can(‘edit_users’, ‘delete_users’)

@include(‘shared._actions’, [
‘entity’ => ‘users’,
‘id’ => $item->id
])

@endcan

nothing show action delete

Yes, it is a bug. @can syntax does not allow you to pass


— Jay two permissions like that. It’s invalid. The second
February 8, 2018
(https://www.qcode
parameter supported should be a Model instance. You
.in/easy-roles-and- can do this instead.
permissions-in-
/
laravel-5-
@if (Gate::check(‘edit_users’) ||
QCode (https://www.qcode.in/)
4/#comment-262)
Gate::check(‘delete_users’))
All about Full Stack Web….
Development
@endif
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Home (http://www.qcode.in)
^C
About (https://www.qcode.in/about/)
— dinesh C:UsersDineshDownloadsNew folder (2)roles-permissions-laravel-master>php
November 8, 2017
artisan db:seed
Contact (https://www.qcode.in/contact/)
(https://www.qcode.in/easy
-roles-and-permissions-in-
laravel-5-4/#comment-197) Do you wish to refresh migration before seeding, it will clear all old data ? (yes/no)
[no]:
> yes

Rolling back: 2017_04_30_014352_create_permission_tables


Rolled back: 2017_04_30_014352_create_permission_tables
Rolling back: 2017_04_30_012311_create_posts_table
Rolled back: 2017_04_30_012311_create_posts_table
Rolling back: 2014_10_12_100000_create_password_resets_table
Rolled back: 2014_10_12_100000_create_password_resets_table
Rolling back: 2014_10_12_000000_create_users_table
Rolled back: 2014_10_12_000000_create_users_table
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrating: 2017_04_30_012311_create_posts_table
Migrated: 2017_04_30_012311_create_posts_table
Migrating: 2017_04_30_014352_create_permission_tables
Migrated: 2017_04_30_014352_create_permission_tables
Data cleared, starting from blank database.
Default Permissions added.

Create Roles for user, default is admin and user? [y|N] (yes/no) [yes]:
>

??????? (yes/no) how to set admin login user login?

/
QCode (https://www.qcode.in/)
how to check box permission saved, please help me
— dinesh
All aboutNovember
Full Stack Web Development
8, 2017
(https://www.qcode.in/easy
Home
-roles-and-permissions-in- About Contact
(http://www.qcode.in)
laravel-5-4/#comment-198) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Home (http://www.qcode.in)
got the output. awesome tutorial thanks and please update more di erent roles
— dinesh and permission based on model
November 8, 2017
About (https://www.qcode.in/about/)
(https://www.qcode.in/easy
-roles-and-permissions-in-
laravel-5-4/#comment-199)
Contact (https://www.qcode.in/contact/)

Nice tutorial
— ELHADI
November 21, 2017
(https://www.qcode.in/easy
-roles-and-permissions-in-
laravel-5-4/#comment-212)

Call to unde ned method IlluminateDatabaseQueryBuilder::defaultPermissions()


— Hoy Nim I have error when I run db:seed, what is the prolem?
December 17, 2017
(https://www.qcode.in/easy
thanks
-roles-and-permissions-in-
laravel-5-4/#comment-216)

It looks you haven’t imported the App /Permission Model,


— Saqueib it’s currently using packages permission model which
December 17, 2017
(https://www.qcode
don’t have defaultPermissions method
.in/easy-roles-and-
permissions-in-
laravel-5-
4/#comment-217)

Is it possible to use the roles with the API:


— oterox Route::middleware(‘auth:api’)->get(‘/user’, function (Request $request)
December 31, 2017
(https://www.qcode.in/easy
How can i test it on Postman?
-roles-and-permissions-in-
laravel-5-4/#comment-223) Thank you so much

/
QCode (https://www.qcode.in/)
Call to unde ned method IlluminateDatabaseQueryBuilder::defaultPermissions()
— Mohammed naseer I have error when I run db:seed, what is the prolem?
All about Full Stack Web Development
January 1, 2018
(https://www.qcode.in/easy
Thanks….
Home
-roles-and-permissions-in- About Contact
(http://www.qcode.in)
laravel-5-4/#comment-224) (https://www.qcode.in/about/) (https://www.qcode.in/contact/
It looks you haven’t imported the App /Permission Model,
— Saqueib it’s currently using packages permission model which
Home (http://www.qcode.in)
January 1, 2018
(https://www.qcode
don’t have defaultPermissions method
.in/easy-roles-and-
About (https://www.qcode.in/about/)
permissions-in-
laravel-5-
4/#comment-225)
Contact (https://www.qcode.in/contact/)

if using table admin do not use table user what is it possible? if you can what to
— Irfan Abdurrasyid change in the settings?
January 3, 2018
(https://www.qcode.in/easy
-roles-and-permissions-in-
laravel-5-4/#comment-229)
Sorry I didn’t get your question?
— Saqueib
January 3, 2018 If you mean to use admin table to store users instead of
(https://www.qcode
.in/easy-roles-and-
users table you can do it by changing the App/User class
permissions-in- property protected $table = admins’;
laravel-5-
4/#comment-230)
Let me know if you need help. You can check out Eloquent
naming convention here
https://laravel.com/docs/5.5/eloquent#eloquent-model-
conventions
(https://laravel.com/docs/5.5/eloquent#eloquent-model-
conventions)

Oke, Thanks a lot of.


— Irfan
Abdurrasyi
d
January 3,
2018
(https://www.
qcode.in/eas
y-roles-and-
permissions-
in-laravel-5-

/
4/#comment-

QCode (https://www.qcode.in/)
231)

All about Full Stack Web Development

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/)
on debug get. i have error below : (https://www.qcode.in/contact/
— Irfan array:4 [▼
Abdurrasyi
“ability” => “view_role”
Home (http://www.qcode.in) d
January 3, “result” => false
2018
“user” => 1
About (https://www.qcode.in/about/)
(https://www.
qcode.in/eas “arguments” => “[]”
y-roles-and-
]
Contact (https://www.qcode.in/contact/)
permissions-
in-laravel-5-
what wrong, i has follow stap by stap
4/#comment-
232) tutorial. i use laravel 5.5

help me : authorize($ability) not wok ng if use guard admin. on Gate error message
— Irfan Abdurrasyid array:4 [▼
January 4, 2018
(https://www.qcode.in/easy
“ability” => “view_order”
-roles-and-permissions-in- “result” => false
laravel-5-4/#comment-234)
“user” => 1
“arguments” => “[]”
]
i use guard web for customer (use table users) and guard admin for administrator
(use table admins). why result in gate always false.

[SymfonyComponentConsoleExceptionCommandNotFoundException]
— Falak naz Command “make:model” is not de ned.
January 10, 2018
(https://www.qcode.in/easy
Did you mean one of these?
-roles-and-permissions-in- make:seeder
laravel-5-4/#comment-241)
make:migration

i get this error trying to run this command

php artisan make:model Post -m -c –resource

/
QCode (https://www.qcode.in/)
Run php artisan make:model Post -mr

All about Full—Stack


Saqueib
Web Development
January 10, 2018
(https://www.qcode
Home .in/easy-roles-and- About Contact
(http://www.qcode.in)
permissions-in- (https://www.qcode.in/about/) (https://www.qcode.in/contact/
laravel-5-
4/#comment-242)

Home (http://www.qcode.in)

About (https://www.qcode.in/about/)
Hey Saqueib, very nice tutorial! It works very well!
Contact (https://www.qcode.in/contact/)
— Eric I just have one question regarding the validation rule of an update method.
January 16, 2018
(https://www.qcode.in/easy
How to ash a error message if the validation fails. I want to keep the syntax with
-roles-and-permissions-in- $this->validate
laravel-5-4/#comment-243)

Is it possible to use something like this?

$test = $this->validate($request, [

'name' => 'required|min:2|max:255'

]);

if( $test->failed() )

flash->error( /*The error*/ )

else

/*Proceed to validation*/

Or I am obligated to use the “old” method by using the Validator model like this
$validator = Validator::make($request->all(), [

'name' => 'required|min:2|max:255'

]);

if ($validator->fails()) /*...*/

Very good post.

/
— José Cage Thanks.
QCode (https://www.qcode.in/)
(https://josecage.com)
January 22, 2018
All(https://www.qcode.in/easy
about Full Stack Web Development
-roles-and-permissions-in-
laravel-5-4/#comment-251)
Home About Contact
(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

I have an error : if I check edit_posts and uncheck the others permissions for the

Home (http://www.qcode.in)
— Yagrademonde User role.
January 28, 2018
(https://www.qcode.in/easy
When I try to access to http://domain/public/posts/4/edit
About (https://www.qcode.in/about/)
-roles-and-permissions-in-
laravel-5-4/#comment-253) (http://domain/public/posts/4/edit)

Contact (https://www.qcode.in/contact/)
I can see the post, but when I want to save my modi cation, I have the error
NotFoundHttpException in Handler.php line 131 : No query results for model
[AppPost] 4.

In my application I wish to not permit to show a list of posts for an user, but with a
given url I want to permit user to edit a certain post.

Can you help me ?

/
QCode (https://www.qcode.in/)
All about Full Stack Web Development

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Home (http://www.qcode.in)

About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)

/
QCode (https://www.qcode.in/)
All about Full Stack Web Development

Home About Contact


(http://www.qcode.in) (https://www.qcode.in/about/) (https://www.qcode.in/contact/

Home (http://www.qcode.in)

About (https://www.qcode.in/about/)

Contact (https://www.qcode.in/contact/)

Copyright © 2020 QCode · Follow: Google (https://plus.google.com/u/0/+MohdSaquibAnsari) · Facebook (https://www.facebook.com/qcode17)


· Twitter (https://twitter.com/mdsaqueib) Contact: E-Mail (mailto:saquibweb@gmail.com) - About (https://www.qcode.in/about) - Privacy Policy
(/privacy-policy/)

You might also like