ACL using Middleware and Role ID

Submitted by laraveltricksmember - 6 years ago

This is a simple solution to create ACL using middleware and role ID. Please follow step by step as shown below. <br> <br>1) create column group_id (int) at users table. <br> <br>2) give value on that column | group_id values: | 1 = Admin | 2 = HR | 3 = Staff 3) create new middleware using php artisan php artisan make:middleware Role 4) Edit the middleware file 5) Edit kernel file and put another line for role class. 6) Set the route and put the role id which allow it to access

// app\Http\Middleware\Role.php

use Closure;
use Illuminate\Contracts\Auth\Guard;

class Role
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    // public function handle($request, Closure $next)
    // {
    //     return $next($request);
    // }


    protected $auth;
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }


    public function handle($request, Closure $next)
    {
            $roles = array_except(func_get_args(), [0,1]);
            foreach($roles as $role) {
                if ($role == $this->auth->user()->group_id) {
                    return $next($request);
                }
            }        
            return response('You don\'t have permission to enter this page.', 404);
    }
}


// app\Http\Kernel.php

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'role' => \App\Http\Middleware\Role::class,
    ];
    
// app\Http\routes.php

Route::group(['prefix' => 'user', 'middleware' => 'role:1,2,3'], function()
{
	Route::get('/', array(
		'uses' => 'HomeController@showUser'
	));
	Route::get('/secret', array(
		'middleware' => 'role:1,2',
		'uses' => 'HomeController@showSecret'
	)); 
});