在 Laravel 中使用 hasRole() 方法可以判定用户是否是指定角色,下面为两个示例:

一、CheckRole 中间件,验证用户是否为给定的「角色」

<?php

namespace AppHttpMiddleware;

use Closure;

class CheckRole
{
    /**
     * 处理传入的参数
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @param  string  $role
     * @return mixed
     */
    public function handle($request, Closure $next, $role)
    {
        if (! $request->user()->hasRole($role)) {
            // Redirect...
        }

        return $next($request);
    }

}

二、判断用户是否为管理员(拥有 admin 角色)

<?php

namespace AppModels;

use IlluminateContractsAuthMustVerifyEmail;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use SpatiePermissionTraitsHasRoles;
use LaravelPassportHasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens,Notifiable,HasRoles;

    public function isAdmin()
   {
       return $this->hasRole('Admin');
   } 
}
@if (Auth::user()->isAdministrator())
	Hello Admin
@else
	Hello standard user
@endif