在 Laravel 中使用 hasRole()
方法可以判定用户是否是指定角色,下面为两个示例:
一、CheckRole 中间件,验证用户是否为给定的「角色」
<?php
namespace App\Http\Middleware;
use Closure;
class CheckRole
{
/**
* 处理传入的参数
*
* @param \Illuminate\Http\Request $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 App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
use Laravel\Passport\HasApiTokens;
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