You can do this through a Middleware
.
You can create a middleware
to verify that the current user is of a certain level. So, you can set this middleware on the routes you set and want only the administrator to access.
Exemplifying better, first you must create a middleware
.
Turn the command php artisan make:middleware AdminCheck
.
It will create a file on 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);
}
}
Then you should add this middleware
at the Http/Kernel
of its application:
protected $routeMiddleware = [
// outros middlewares
'auth.admin' => App\Http\Middleware\AdminCheck::class
];
Next on 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
});
Remarks
In what part $request->user()->admin == false
i am doing a check to see if this user has been registered in my database as an administrator. In this case, it is not necessary for you to do as I did, but it is important that you have a way to differentiate an ordinary user from an administrator user. This way you will have to elaborate. I am commenting on this because in your question you quote that they are registered "admin and common user, both in the User table, with the same attributes.".
Very good, the example of the legal 403 +1
– Guilherme Nascimento
Until then I have differentiated these two users by registration in a third table. Ordinary users have a register in the session table. Now, I believe I will have to create an attribute in the User table that can differentiate them.
– Kaninchem
Very good example, I’m moving here! Thank you!
– Kaninchem
@Kaninchem the way you store who is admin or ordinary does not matter, you just need to write a code consistent with what you already have.
– Wallace Maxters
@Kaninchem, creates a third table with the username_type name, then you relate the two, the admin, to the user for it, and leaves the rules of the user types accessible from middleware
– Renan Oliveira