Route restrictions with Laravel

Asked

Viewed 451 times

0

Good afternoon.

How can I restrict some specific routes with Laravel?

For example. If I have an e-commerce I will have users administrators who can access the administrative panel routes and all other routes of the site. But I will also have the users/customers say so. These may access the routes of the site and your login in the client area, but they may not access the administrative panel routes.

Another example:

Routes (/admin/home) (/admin/products) (/admin/edit-products) -> Only administrators can access these routes.

(/My-shopping) (/my-cart) -> These routes customers and administrators can access.

But if I do the same authentication for users/clients and administrators, I won’t be able to do that restriction. If the guy is logged in he will be able to access any route of my system, regardless of whether he is administrator or client.

Do you understand? You can help me?

1 answer

2


You can use Laravel Middleware, you create a specific rule and create a grouping of routes for example:

Route::group(['middleware' => ['auth','check_permissions']], function () {
   // TODAS SUAS ROTAS QUE VÃO SER VALIDADAS POR ESSE MIDDLEWARE
})

In this grouping, I’m saying he has to be authenticated and respect the rules of Middleware Checkpermissions

my file Checkpermissions:

class CheckPermissions {

     /**
       * Handle an incoming request.
       *
       * @param  \Illuminate\Http\Request $request
       * @param  \Closure $next
       * @return mixed
     */
    public function handle ($request, \Closure $next)
    {
        $isAdmin = Auth::user()->is_admin;

        if ($isAdmin) {
            return $next($request);
        }
        return redirect()->route('home');
    }

}

It will check if the user is admin, if it is not redirects to home, otherwise it goes to the route being requested.

You have to add your middleware to the Kernel.php file in the variable $routeMiddleware:

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'check_permissions' => CheckPermissions::class
    ];

If you have questions, follow the documentation link:

https://laravel.com/docs/5.3/middleware

  • Good afternoon. I will implement here and give you a feedback. I appreciate the help.

  • Good morning. It worked! Thanks partner.

  • You’re welcome @Mauritississimo if you can accept the answer as correct, thank you! Hug

Browser other questions tagged

You are not signed in. Login or sign up in order to post.