简体   繁体   English

Laravel 5.5-仅获得管理员用户

[英]Laravel 5.5 - Only Get Admin Users

I am getting a users details in a Laravel 5.5 controller like this... 我正在这样的Laravel 5.5控制器中获取用户详细信息...

$user = Auth::user();

But I want to do a check and see if the user has 'user_type' set to 'admin' 但是我想检查一下用户是否将'user_type'设置为'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. 正如你可以看到这里 ,为用户默认的迁移没有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. 您可以(例如)使用laravel权限和角色(Spatie)来为您完成工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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