Aipo
Aipo

Reputation: 1985

How to protect admin area from users by role in laravel 5.6?

I was looking for simple Laravel 5.6+ version roles and users solution. I want to have one users table. So I added user_type in my table as string in

$table->enum('role', ['admin', 'user']);

Which files should I create or update to protect everything under /admin route. And do not let to use admins routes for users?

Upvotes: 0

Views: 196

Answers (1)

Mario Haubenwallner
Mario Haubenwallner

Reputation: 1925

You should create a middleware that is active in all /admin routes. In this middleware you should check if the user that is logged in (Auth::user()) has the "admin"-role.

Auth::user() references the User-model.

So in the User-model you can create a function like isAdmin():

public function isAdmin()
{
    return $this->role === 'admin'
}

In the Middleware (or wherever you want it) you can just write

if(Auth::user()->isAdmin()) {
    // do something if user is admin
} else {
    // do something if user is not admin
}

Since it is in the User-model you can also write $user->isAdmin() for regular user models.

Upvotes: 1

Related Questions