How can I differentiate authentications in laravel? Example: Administrator and Common User without using multauth

6

How can I differentiate routes to the same auth? I have a User table and I have registered two types of user: admin and common user, both in the User table, with the same attributes.

How can I differentiate the routes that will appear for both the adm and the average user, since each one has access to different things?

You can indicate documentation for this case

    
asked by Kaninchem 07.12.2016 в 18:42
source

1 answer

7

You can do this through Middleware .

You can create middleware to check if the current user is of a certain level. So you can have this middleware defined on the routes you are defining and that you want only the administrator to access.

For example, you should first create a middleware .

Run the command php artisan make:middleware AdminCheck .

It will create a file in app/Http/Middlewares/AdminCheck.php . Then edit it, as in the case below:

class AdminCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->user()->admin == false) {
            return abort(403, "Acesso não autorizado");
        }

        return $next($request);
    }
}

Next, you should add this middleware to Http/Kernel of your application:

protected $routeMiddleware = [
    // outros middlewares
     'auth.admin' => App\Http\Middleware\AdminCheck::class
];

Next in your routes, you define a group of routes that can be accessed only by this group:

Route::group(['middleware' => ['auth', 'auth.admin'], function () {
      // Minhas rotas da administração aqui
});

Notes

In the $request->user()->admin == false excerpt I'm doing a check to see if this user was registered in my database as an administrator. In case, it is not necessary that you do the same I did, but it is important you have a way to differentiate an ordinary user from an admin user. This way you will have to work out. I am commenting on this because in your question you cite that you are registered "admin and common user, both in the User table, with the same attributes."     

answered by 07.12.2016 / 19:05
source