简体   繁体   中英

Laravel 5.5 - Only Get Admin Users

I am getting a users details in a Laravel 5.5 controller like this...

$user = Auth::user();

But I want to do a check and see if the user has 'user_type' set to 'admin'

I know I can do a further check once I have the users info but is there a way to combine this into the one statement?

Create a method in User model:

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

Then use it anywhere in your code:

if (auth()->user()->isAdmin())

Or just do it manually each time:

if (auth()->check() && auth()->user()->user_type === 'admin')

You can even create a global helper and do this:

@if (isAdmin())

这样,您可以检索已认证用户的user_type

$user = Auth::user()->user_type;

As you can see here , the default migration for users does not have a user_type. Hence, if you want to give users certain privileges, you'll have to create it first.

I recommand using a out-of-the-box package. You can (for example) use the package laravel permissions and roles (by Spatie) to do the work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM