我在使用Auth::user((确定权限时遇到问题->can((。例如Auth::user((->can('trunk.index(总是返回错误;
但我有个问题。如果我转储$user->getPermissionsViaRoles((,我会得到一个很大的结果。
我正在使用不同的表user_view表。根据它,我在Auth.php文件中进行了更改。登录操作正常。
'providers' => [
'users' => [
'driver' => 'self-eloquent',
'model' => AppModelsUserView::class,
]
],
但当我尝试通过Auth::user((检查权限时,->can('trunk.index(,则它在错误下面给出错误。
Call to undefined method App\Models\UserView::can()
下面是我的UserView模型代码。
<?php
namespace AppModels;
use IlluminateAuthAuthenticatable;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use IlluminateContractsAuthAuthenticatable as AuthenticatableContract;
use IlluminateContractsAuthAccessAuthorizable as AuthorizableContract;
use IlluminateSupportFacadesHash;
use SpatiePermissionTraitsHasRoles;
use LaravelLumenAuthAuthorizable;
use LaravelSanctumHasApiTokens;
class UserView extends Model implements AuthenticatableContract
{
use Authenticatable;
use HasFactory;
use HasRoles;
use HasApiTokens;
protected $table = 'user_view';
protected $primaryKey = "user_id";
protected $fillable = [
'username', 'password',
];
protected $guarded = [];
public function getAuthPassword()
{
return ['password' => $this->attributes['user_password']];
}
// public function can($abilities, $arguments = []) {
// }
}
如果我遗漏了什么,请帮帮我。非常感谢。
您使用的是自定义User
模型,该模型不实现IlluminateContractsAuthAccessAuthorizable
接口和IlluminateContractsAuthAccessGateAuthorizable
特性。实际上,您确实有一个用于该接口的导入,但它没有在任何地方使用。
还要小心现有的导入LaravelLumenAuthAuthorizable
。我不熟悉Lumen,但这可能是一个不同的实现/错误的导入。
您基本上需要用以下两行更新您的模型:
<?php
namespace AppModels;
use IlluminateAuthAuthenticatable;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use IlluminateContractsAuthAuthenticatable as AuthenticatableContract;
use IlluminateContractsAuthAccessAuthorizable as AuthorizableContract;
use IlluminateFoundationAuthAccessAuthorizable; // <-- add import
use SpatiePermissionTraitsHasRoles;
use LaravelSanctumHasApiTokens;
class UserView extends Model implements AuthenticatableContract,
AuthorizableContract // <-- add interface
{
use Authenticatable;
use Authorizable; // <-- add trait
use HasFactory;
use HasRoles;
use HasApiTokens;
// ... other code ...
}