Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Laravel 5 Simple ACL - Protect routes by an account / role type

#Laravel 5 Simple ACL manager

Protect your routes with user roles. Simply add a 'role_id' to the User model, install the roles table and seed if you need some example roles to get going.

If the user has a 'Root' role, then they can perform any actions.

Installation

Simply copy the files across into the appropriate directories, and register the middleware in App\Http\Kernel.php

Then specify a 'roles' middleware on the route you'd like to protect, and specify the individual roles as an array:

Route::get('user/{user}', [
     'middleware' => ['auth', 'roles'],
     'uses' => 'UserController@index',
     'roles' => ['administrator', 'manager']
]);

If you found this ACL manager helpful please give this repo a star, and give me a follow. Any questions, please leave a comment.

<?php namespace App\Http\Middleware;
// First copy this file into your middleware directoy
use Closure;
class CheckRole{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Get the required roles from the route
$roles = $this->getRequiredRoleForRoute($request->route());
// Check if a role is required for the route, and
// if so, ensure that the user has that role.
if($request->user()->hasRole($roles) || !$roles)
{
return $next($request);
}
return response([
'error' => [
'code' => 'INSUFFICIENT_ROLE',
'description' => 'You are not authorized to access this resource.'
]
], 401);
}
private function getRequiredRoleForRoute($route)
{
$actions = $route->getAction();
return isset($actions['roles']) ? $actions['roles'] : null;
}
}
<?php
// Register the new route middleware
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
'roles' => 'App\Http\Middleware\CheckRole',
];
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model {
protected $table = 'roles';
public function users()
{
return $this->hasMany('App\User', 'role_id', 'id');
}
}
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRolesTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('role', function($table) {
$table->increments('id');
$table->string('name', 40);
$table->string('description', 255);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('role');
}
}
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Role;
class RoleTableSeeder extends Seeder{
public function run()
{
if (App::environment() === 'production') {
exit('I just stopped you getting fired. Love, Amo.');
}
DB::table('role')->truncate();
Role::create([
'id' => 1,
'name' => 'Root',
'description' => 'Use this account with extreme caution. When using this account it is possible to cause irreversible damage to the system.'
]);
Role::create([
'id' => 2,
'name' => 'Administrator',
'description' => 'Full access to create, edit, and update companies, and orders.'
]);
Role::create([
'id' => 3,
'name' => 'Manager',
'description' => 'Ability to create new companies and orders, or edit and update any existing ones.'
]);
Role::create([
'id' => 4,
'name' => 'Company Manager',
'description' => 'Able to manage the company that the user belongs to, including adding sites, creating new users and assigning licences.'
]);
Role::create([
'id' => 5,
'name' => 'User',
'description' => 'A standard user that can have a licence assigned to them. No administrative features.'
]);
}
}
<?php
Route::get('user/{user}', [
'middleware' => ['auth', 'roles'], // A 'roles' middleware must be specified
'uses' => 'UserController@index',
'roles' => ['administrator', 'manager'] // Only an administrator, or a manager can access this route
]);
<?php
// The User model
public function role()
{
return $this->hasOne('App\Role', 'id', 'role_id');
}
public function hasRole($roles)
{
$this->have_role = $this->getUserRole();
// Check if the user is a root account
if($this->have_role->name == 'Root') {
return true;
}
if(is_array($roles)){
foreach($roles as $need_role){
if($this->checkIfUserHasRole($need_role)) {
return true;
}
}
} else{
return $this->checkIfUserHasRole($roles);
}
return false;
}
private function getUserRole()
{
return $this->role()->getResults();
}
private function checkIfUserHasRole($need_role)
{
return (strtolower($need_role)==strtolower($this->have_role->name)) ? true : false;
}
@ultramarshall

This comment has been minimized.

Copy link

commented Feb 23, 2015

I Just copy the above code , when I run the " db : seed ".
I received a message "I just stopped you getting fired. Love, Amo.",
This really makes me surprisingly... please help me to understand, thanks.

@teslaji

This comment has been minimized.

Copy link

commented Feb 23, 2015

@ultramarshall

check this line in config/app set as

'debug' => env('APP_DEBUG'),

@pablomaurer

This comment has been minimized.

Copy link

commented Feb 23, 2015

lol.. search for the string and you will find out =) dont just copy try to read it.
But what i think it should not be a one-to-one relationship instead a one-to-many?

@amochohan

This comment has been minimized.

Copy link
Owner Author

commented Feb 25, 2015

ultramarshall, That code in the seeder is intended to do exactly that, to stop silly mistakes by running the seed accidentally in a production environment. It should only be run in a dev environment.

@amochohan

This comment has been minimized.

Copy link
Owner Author

commented Feb 25, 2015

mnewmedia: you're right, you could define the relationship as a hasMany but it depends on your individual requirements. For my business, we need one user to have one role (they can inherit permissions in other ways, which is outside of the scope of this simple ACL system).

@ashishsanjayrao

This comment has been minimized.

Copy link

commented Mar 5, 2015

I would like to point out an issue: In the DB seed and migration for roles table, the table name is given as "role" instead of "roles". In the model the table is defined as "roles". Otherwise, it's a great gist!

Thanks.

@faisalahsan

This comment has been minimized.

Copy link

commented Apr 2, 2015

@drawmyattention this is nice piece of code. I am new to Laravel and i am using default Login System. How can i integrate this code in default. Because there is not exists route you have define

Route::get('user/{user}', [ 'middleware' => ['auth', 'roles'], // A 'roles' middleware must be specified 'uses' => 'UserController@index', 'roles' => ['administrator', 'manager'] // Only an administrator, or a manager can access this route ]);

@vijaysebastian

This comment has been minimized.

Copy link

commented Apr 23, 2015

thanks.... it works....... But i am using a lot of resource in my route, so do you have any idea to fix that in one shot. Otherwise i have to change my entire route !

@amochohan

This comment has been minimized.

Copy link
Owner Author

commented Apr 24, 2015

@vijaysebastian I'm not entirely sure what you mean. Can you please elaborate with some code?

@huiralb

This comment has been minimized.

Copy link

commented Apr 28, 2015

Excuse me, I am new in Laravel.
i have any question for this section

private function getUserRole()
{
    return $this->role()->getResults();
}

where i get the getResults() function ?
what this might get() ?

@amochohan

This comment has been minimized.

Copy link
Owner Author

commented Apr 29, 2015

Pay particular attention to the method's role() syntax. The () denotes that an instance of the relationship builder is returned. From this the getResults method can be accessed from the Eloquent builder.

See Illuminate\Database\Eloquent\Relations\BelongsTo, line 55 for the getResults() method.

public function getResults()
{
    return $this->query->first();
}

I do appreciate this is far from the optimal way of achieving the given result.

@Nemutagk

This comment has been minimized.

Copy link

commented Apr 30, 2015

I have my file "route.php", how i can modified to implement the ACL?

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::group(array('domain' => 'domain.com'), function() {
    Route::get('/', 'Site\IndexController@index');
    Route::controller('index','Site\IndexController');
});

Route::group(array('domain' => '{app}.domain.com', 'before' => ' domain.com'), function() {
    Route::get('/', 'Lual\IndexController@index');
    Route::controllers([
        'index' => 'Lual\IndexController',
        'auth' => 'Lual\AuthController'
        ]);
});


//verisón de desarrollo/
Route::group(array('domain' => '192.168.0.102'), function() {
    Route::get('/', 'LualController@index');

    Route::controllers([
        'index' => 'Lual\IndexController',
        'auth' => 'Auth\AuthController'
    ]);
});

View::composer('partials.lang','App\Composer\LangComposer');
@amochohan

This comment has been minimized.

Copy link
Owner Author

commented Apr 30, 2015

This Gist won't work out of the box with route groups. You'll need to apply the middleware to each individual route within the groups.

@pathros

This comment has been minimized.

Copy link

commented May 16, 2015

How do you allow guest users with no roles to view, for example, the index page?

@amochohan

This comment has been minimized.

Copy link
Owner Author

commented May 19, 2015

@pathros, simple; simply don't apply the middleware to that route.

@JafariM

This comment has been minimized.

Copy link

commented May 20, 2015

It works great.Thanks

@charlesferreira

This comment has been minimized.

Copy link

commented May 28, 2015

Great solution. Just what I was looking for. Many thanks! <3

@gservat

This comment has been minimized.

Copy link

commented Jun 1, 2015

How do you get the seeder to work with mass assignment protection?

@gservat

This comment has been minimized.

Copy link

commented Jun 1, 2015

Ah, never mind... database seeder does a Model::unguard() which takes care of that.

@gservat

This comment has been minimized.

Copy link

commented Jun 1, 2015

@drawmyattention, how hard do you think it would be for this Role middleware to work with Route::resource() type routes? I use a few of them and I rather not have to specify each get/post/patch/delete route myself so that I can hook in the middleware.

@ginc0der

This comment has been minimized.

Copy link

commented Jun 3, 2015

Are you sure with this code??
if($request->user()->hasRole($roles) || !$roles)
{
return $next($request);
}

@amochohan

This comment has been minimized.

Copy link
Owner Author

commented Jun 3, 2015

@ginc0der This is absolutely intended. Not all routes require a user to have a given role. In the absence of a role being returned from the getRequiredRoleForRoute() method, the next request is returned.

@amochohan

This comment has been minimized.

Copy link
Owner Author

commented Jun 3, 2015

@gservat Unfortunately not. Feel free to submit a fork if you manage to implement that.

@sebazamorano

This comment has been minimized.

Copy link

commented Jun 17, 2015

Thanks!!!!!!, Is very cool solution. very easy

@digitalohm

This comment has been minimized.

Copy link

commented Jun 19, 2015

Has anyone run into

BadMethodCallException in Builder.php line 1992:
Call to undefined method Illuminate\Database\Query\Builder::roles()

@derylihs

This comment has been minimized.

Copy link

commented Jul 10, 2015

you use it in route, what about i want to implement it in __construc at my controller ?

@ToNyOyO

This comment has been minimized.

Copy link

commented Jul 22, 2015

A dumb question:

Why does this work...
$users = User::all()->where('role_id', 5);

But this does not...
$users = User::all()->where('role_id', '<=', 4);

How can I get all the users that aren't just users? I'm using the Laravel 5.1 Auth stuff.

Thanks!

@amochohan

This comment has been minimized.

Copy link
Owner Author

commented Jul 31, 2015

@ToNyOyO you should really use the get() method instead of all(). Something like:

$users = User::where('role_id', '<=', 4)->get();
@amochohan

This comment has been minimized.

Copy link
Owner Author

commented Jul 31, 2015

@dbassassin You've probably forgotten to add the roles() relationship function on the User model.

@derylihs You can't inject middleware into a controller as that defeats the purpose of middleware. It should be executed before the Controller methods are hit.

@kripastha

This comment has been minimized.

Copy link

commented Aug 13, 2015

Thanks a lot. its easy !!!

@Siddhesh1512

This comment has been minimized.

Copy link

commented Aug 19, 2015

Great tutorial. Thanks.

@arafatx

This comment has been minimized.

Copy link

commented Aug 24, 2015

Sorry I don't understand this implementation. What does the role_id refers too? Do we need to create another table called role_user and specify role_id there? Not mentioned in the tutorial.

@kasirye

This comment has been minimized.

Copy link

commented Sep 2, 2015

can this be implemented on laravel 5.1.x, otherwise your code is good and clean

@milos-stankovic

This comment has been minimized.

Copy link

commented Sep 17, 2015

Works in 5.1.x with many to many same as one to one. Documentation is clear how pivot works.
Thanks for this! :))

@rajgit2012

This comment has been minimized.

Copy link

commented Sep 29, 2015

Struggling to run the route using the UserController. Is there any roles and user relationship needed? Confused!

@pericoandrea

This comment has been minimized.

Copy link

commented Oct 5, 2015

vary usefull thanks 🎯 👍

@ecairol

This comment has been minimized.

Copy link

commented Oct 11, 2015

Simple to understand and implement. Very elegant. Thanks!

@tanveerahdar

This comment has been minimized.

Copy link

commented Oct 22, 2015

i am new to laravel. please tell how can we assign the roles to the user. and how to check the roles in the controller. thank you...

@amochohan

This comment has been minimized.

Copy link
Owner Author

commented Oct 23, 2015

@tanveerahdar you may want to refer to the Laravel Eloquent relationships documentation for help on how to assign roles. To check a user's role in a controller, something like $roles = $user->roles; would lazy load the roles relationship.

@M165437

This comment has been minimized.

Copy link

commented Oct 29, 2015

Nice gist! To simplify it, you could pass multiple roles as parameters to the middleware with PHP 5.6+

// RolesMiddleware
public function handle($request, Closure $next, ...$roles) { ... }

// Route
Route::get('post/edit', ['middleware' => 'roles:admin,editor', function () { ... }]);

Take a look at Variable-length argument lists

@wotta

This comment has been minimized.

Copy link

commented Nov 24, 2015

We need to login before we can try this ?

@Devsome

This comment has been minimized.

Copy link

commented Jan 11, 2016

Is is possible to check in a *blade.php if the user is role Administrator ?
//update: found it out. Thanks for your great tutorial

@williansebastiao

This comment has been minimized.

Copy link

commented Feb 4, 2016

I'm using laravel 5.2, I can use the ACL for multiple auth? Is is possible to check in a *blade.php if the user is role Administrator ?

@sekretuser

This comment has been minimized.

Copy link

commented Feb 10, 2016

Nice, thanks for share dude ...

@hmojtaba

This comment has been minimized.

Copy link

commented Feb 11, 2016

thank you very much for this really easy and working approach.
at first i was confused how to manage role_id, but now it just works! and works fine.
I liked it.
👍
💯
i also redirected to page accessViolation instead of that error message. Nice piece of work.

@heilgar

This comment has been minimized.

Copy link

commented Feb 24, 2016

thx for this simple solution.

williansebastiao, yes it possible
@if( Auth::User()->hasRole(['Partner', 'Moder']) )
@endif

@acidrainz

This comment has been minimized.

Copy link

commented Mar 8, 2016

THis does not work on laravel 5.2

@joenefloresca

This comment has been minimized.

Copy link

commented Mar 22, 2016

What if I am using a resource route and I just want to apply the middleware in a specfic part of a resource route? Let's say index.

Route::group(['middleware' => ['auth', 'roles'], 'roles' => ['Administrator']], function()
{
Route::resource('changeschedule', 'ChangeScheduleController');
});

That code will be applied to routes under changeschedule resource. What if I want it to be in the index only? Thanks

@cbiong

This comment has been minimized.

Copy link

commented Mar 27, 2016

How to implement this part of code inside public function __construct() of controller?

'middleware' => ['auth', 'roles'],
     'roles' => ['administrator', 'manager']
@amochohan

This comment has been minimized.

Copy link
Owner Author

commented Mar 30, 2016

@joenefloresca this code won't work with route resources
@cbiong This middleware is executed before a controller is instantiated. Therefore that's not possible.

@pericoandrea

This comment has been minimized.

Copy link

commented Mar 31, 2016

@drawmyattention @joenefloresca @cbiong You can set an Action to de route in the constructor of controller.
public function __construct(Request $request, Guard $auth) { $this->request->route() ? $this->request->route()->setAction(['roles' => ['administrator']]) : ''; $this->middleware('auth'); $this->middleware('roles'); }

@firsov

This comment has been minimized.

Copy link

commented Apr 25, 2016

Roles_table_migration.php has table role
RoleTableSeeder.php has table role
Role.php has table roles
Whats up?

@jinser

This comment has been minimized.

Copy link

commented Apr 29, 2016

Hi just tried out the code and it works for me on Laravel 5.2.

The migration table for the users table needs a "role_id" field though, so using the same naming convention, a file called "Users_table_migration.php" needs to be created with that column.

@ronayumik

This comment has been minimized.

Copy link

commented May 11, 2016

The first comment surprise me too, haha :D

@z900collector

This comment has been minimized.

Copy link

commented May 23, 2016

I found a few issues.

  1. You need to add the syntax for the 'users' table changes to your doco: alter table users add role_id int unsigned not null;
  2. Then set the users role_id's otherwise it does not work.
  3. Role.php has "roles" (as mentioned earlier).

Seams to work ok after this.

@benmclendon

This comment has been minimized.

Copy link

commented Jun 7, 2016

Laravel newbee, apologies in advance. Laravel 5.2.35

My Route:

Route::get('portal', [
    'middleware' => ['auth', 'roles'], // A 'roles' middleware must be specified
    'uses' => 'UserController@index',
    'roles' => ['user'] // Only an administrator, or a manager can access this route
]);

I'm getting this: "ReflectionException in Route.php line 280: Method App\Http\Controllers\UserController::index() does not exist"
UserController.php is your User.php

If I add an index function to the controller I get: "BadMethodCallException in Builder.php line 2345: Call to undefined method Illuminate\Database\Query\Builder::hasRole()"

I've made the adjustments mentioned above.

Suggestions?

@gkimpson

This comment has been minimized.

Copy link

commented Jun 17, 2016

I am using Laravel 5.2.38 and have followed the steps above included the fixes and when I try to run php artisan migrate I get the following error:

[Symfony\Component\Debug\Exception\FatalErrorException] Class '' not found

Any ideas?

@dldelante

This comment has been minimized.

Copy link

commented Jun 22, 2016

Just learned laravel and php and still a lot to learn. I just want to share that I use spatie-permissions to create roles and permissions then through this Simple ACL Manager I was able to understand a thing or two about authentication.
So instead of using the 'handle' method in VerifyRole.php I used the 'handle' method from zizaco/entrust and now I can use this in route groups. See zizaco/entrust on how to use the 'role' on route groups.

@mkillua

This comment has been minimized.

Copy link

commented Jul 22, 2016

gkimpson your problem is because this migrate copy and pasted don't have a date.
so, try this - > php artisan make:migration create_roles_table
after, you need modify the date of generated migration, 2016 to 2013 for example.(because exist foreign key in users)
now copy and past the original migrate method

@aacook

This comment has been minimized.

Copy link

commented Jul 24, 2016

Thanks - any suggestions on how best to set a user's role? Here's how I'm currently doing it.

$role = Role::where('name', '=', 'client')->first();
$user->role_id = $role->id;
@amochohan

This comment has been minimized.

Copy link
Owner Author

commented Jul 28, 2016

@aacook if you have a role() relationship on the User model you can simply do $user->role()->associate($role);

@lcdss

This comment has been minimized.

Copy link

commented Jul 29, 2016

@aacook $user->role()->associate(Role::whereName('client')->first());

@ssirjann

This comment has been minimized.

Copy link

commented Aug 19, 2016

can anyone suggest on this, http://stackoverflow.com/questions/38827474/laravel-5-polymorphic-relationship-with-foreign-key .
I need to add polymorphic relationship between user types, as well as have a separate role table for setting permissions.

@kyoukhana

This comment has been minimized.

Copy link

commented Aug 22, 2016

I currently have a users.php with the following code under App/user.php. Was wondering where the User code is suppose to go. Also I didn't see any examples on how to use this using route::

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

/**
 * App\User
 *
 * @mixin \Eloquent
 */
class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

@blorange2

This comment has been minimized.

Copy link

commented Aug 22, 2016

Can you grab the name of the role in a blade?

@amochohan

This comment has been minimized.

Copy link
Owner Author

commented Aug 22, 2016

@blorange2 Yes, simply inject the User object into your template and then you can use $user->role->name

@nicolasdanelon

This comment has been minimized.

Copy link

commented Aug 23, 2016

can you re-write this code in go-lang ?
hahaha just kidding.
Grate job, I'll use this with my REST API ;)

@skysanket

This comment has been minimized.

Copy link

commented Aug 30, 2016

How can I use with resource routes.?

@LexPr

This comment has been minimized.

Copy link

commented Aug 30, 2016

TANKS

@AngeloMerlo

This comment has been minimized.

Copy link

commented Oct 5, 2016

I'm using 5.3 laravel and I have a problem I do not know how to solve. Could anyone help me, please?

Route: Route::get('/', function () { return view('welcome'); });
error: FatalThrowableError in CheckRole.php line 20: Call to a member function hasRole() on null

@greatsami

This comment has been minimized.

Copy link

commented Oct 13, 2016

Update:
I solved my issue. by adding this codes in app\Exceptions\Handler.php @ unauthenticated function:

$route = Route::getCurrentRoute()->getPath();
switch($route) {
     case 'admin':
             $login = '/admin/login';
             break;
     default:
             $login = '/login';
             break;
}

return redirect()->guest($login);

Now its working :)

Hi

I used your tutorial and every thing is OK.
i built admin layouts as separate theme, when I write in url: (http://multiauth.dev/admin) (and not logged) it redirect me to original login.
I need to redirect me to (http://multiauth.dev/admin/login).

i have a note if logged to admin i can see (http://multiauth.dev/admin/login) page.

How i can do it?
note: I'm newbie with laravel

@JoseCage

This comment has been minimized.

Copy link

commented Oct 19, 2016

Thank you o much for this snnipet..

Works for me.. 👍 📦 💯

@Shkeeny

This comment has been minimized.

Copy link

commented Nov 24, 2016

Hello, I'm new to Laravel, how do I add a restriction to this route: Route::resource('users', 'UserController'); ? Thanks in advance!

@amochohan

This comment has been minimized.

Copy link
Owner Author

commented Nov 28, 2016

@Shkeeny this code won't work with route resources out of the box.

@k9uma

This comment has been minimized.

Copy link

commented Dec 7, 2016

Hai, I used this method a couple months ago L5.0, just tried it with 5.3 and i keep getting the same error about not finding the CheckRole class, something like this "ReflectionException in Container.php line 749:
Class App\Http\Middleware\CheckRole does not exist"
Any ideas??

@yourzed

This comment has been minimized.

Copy link

commented Dec 7, 2016

Hi @drawmyattention,
your code works great with my project. The thing is that it only works for two roles, when I do a thirth, it passes the autenthication, but the view shows a 500 error with no more info. My routes are like this:

Route::group(['middleware' => ['auth','roles'], 'roles' => ['Administrator']], function() {
Route::controller('/system/dashboard', 'AdminController');
.... THIS WORKS
});

Route::group(['middleware' => ['auth','roles'], 'roles' => ['Role1']], function() {
Route::controller('/system/dashboard', 'AdminController');
.... THIS WORKS
});

Route::group(['middleware' => ['auth','roles'], 'roles' => ['Role2']], function() {
Route::controller('/system/dashboard', 'AdminController');
.... IT Goes to the controller, but when showing the view: error 500...
});

Any idea of why? Of course I have all the roles on the database. And If I delete the last route group and try to login with that customer, it shows the Insuficient role, you are not allowed, correctly.
Thanks in advance

@amochohan

This comment has been minimized.

Copy link
Owner Author

commented Dec 8, 2016

@yourzed if it gets to the controller, the middleware has allowed the request. If you're getting a 500 error from the view, I don't see how that'd related. You may be referring to a value that doesn't exist, which causes blade to thrown an exception.

@yourzed

This comment has been minimized.

Copy link

commented Dec 9, 2016

Many thanks @drawmyattention, finally I managed to work it ! I had to made some changes on the app.php and that was all. Thanks, it works like charm on laravel 5.1 ;)

@daino92

This comment has been minimized.

Copy link

commented Dec 13, 2016

@drawmyattention Hello mate! So I get this error:

BadMethodCallException in Builder.php line 2405:
Call to undefined method Illuminate\Database\Query\Builder::role()

This is my sample route:

Route::get('/admin/products', [
'uses' => 'AdminController@adminProducts',
'as' => 'admin.products',
'middleware' => ['auth', 'roles'],
'roles' => ['admin'],
]);

Can you tell me what's going on? Also I have added the roles() relationship function on the User model.

@rutvij2292

This comment has been minimized.

Copy link

commented Jan 17, 2017

@drawmyattention Thanks for the simple solution for ACL. I would like to add few lines in controller to work with Route::group.

Here's my suggestion.

`
Route::group(['middleware' => ['auth', 'roles'], 'roles' => ['admin']], function() {
Route::get('admin/{user_id}/edit/{course_id}/reasons/{reason_id}', [
'uses' => 'AdminController@reasonsShowAndEdit'
]);

    Route::get('admin/{user_id}/edit/{course_id}', [
        'uses' => 'AdminController@journalsShow',
    ]);

    Route::get('admin/home', [
        'uses' => 'AdminController@index',
    ]);
});

`

This works like a charm. Thanks once again.

@rexdarel

This comment has been minimized.

Copy link

commented Sep 14, 2017

Hi, im using the make:auth and I'm new to laravel. I have added a column "type" in the users table to determine if the user is an admin or super admin or just a user. I was able to protect the components of my view files (like buttons, tables) using the "type" column but the problem is the routes of the super admin can still access by the admin... My question is, how can I use your solution on my current situation? Or do you have any idea how to protect the routes base on the column "type"?

@candrasetiadi

This comment has been minimized.

Copy link

commented Mar 3, 2018

Hello...
Everyhting was work for me.
But How i make the roles specified on controller? you make it on route file like this 'roles' => ['admin', 'superadmin']
because i have dynamic roles on my roles table.

please help me. thanks

@gitongacollin

This comment has been minimized.

Copy link

commented Oct 10, 2018

Hi, I'm new to Laravel
Every time I try to check if the roles are working I'm getting this error
Call to a member function hasRole() on null
I create a route to try check
Kindly help

Here is the snippet of my route
`Route::group(['middleware'=>['authen','roles'],'roles'=>['Root']],function(){
//for Root

Route::get('/createUser',function(){
	echo "This is for Root test";
});`
@miladjamali

This comment has been minimized.

Copy link

commented Aug 25, 2019

nice this helped me much thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.