Search code examples
laravellaravel-5routeslaravel-authorization

Prevent role-specific users from accessing route


I have 2 roles, which is admin and user. Now when logging in, the admin goes to the dashboard route while the user goes to home. When user is logged in and changes the url to http://127.0.0.1:8000/dashboard it can access the admin's panel and I don't want that. How can I do achieve this?

PS. I'm new to Laravel


Solution

  • The good practice for this is usage of Middewares. Create middlewares for admins and users (I'll do that only for admins, you can do that similarly for users):

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Support\Facades\Auth;
    
    class AdminMiddleware
    {
        public function handle($request, Closure $next)
        {
            if(Auth::check()){
                // check auth user role (I don't know how you can implement this for yourself, this is just for me)
                if(Auth::user()->role->name == 'admin'){
                    return $next($request);
                } else {
                    return redirect()->route('admin.dashboard'); // for admins
                }
            }
    
            return redirect()->route('main'); // for users
        }
    }
    

    In "app/Http/Kernel.php" in $routeMiddleware array register that (add to end of that array).

    'Admin' => \App\Http\Middleware\AdminMiddleware::class,
    

    Now if you are using all requests in "routes/web.php" (actually I think it does), then you can use routes like this for admins:

    // USER ROUTES
    Route::get('/', 'FrontController@main')->name('main');
    
    // ADMIN ROUTES
    Route::group([
        'as' => 'admin.',
        'middleware' => [ 'Admin' ],
    ], function () {
        Route::get('dashboard', 'AdminController@dashboard');
    });
    

    Refresh caches via "php artisan config:cache". Try it!