无法为Laravel中的模型类设置属性

无法为Laravel中的模型类设置属性,laravel,dependency-injection,model,laravel-6,Laravel,Dependency Injection,Model,Laravel 6,我正在尝试在用户类上添加依赖项注入,经过几个小时的尝试,我发现如下方法: 我将此代码添加到App\Models\User类中 我已经检查了$this->roleService值,它工作正常,但当我尝试在函数中使用它时: 此函数对null上的成员函数isAdmin()抛出错误调用。当我登录$this->roleService时,它返回null 任何人都可以解决这个问题?为您的模型创建一个自定义访问器,并从中获取/设置值 public function getRoleServiceAtt

我正在尝试在用户类上添加依赖项注入,经过几个小时的尝试,我发现如下方法:

  • 我将此代码添加到
    App\Models\User
    类中
  • 我已经检查了
    $this->roleService
    值,它工作正常,但当我尝试在函数中使用它时:
  • 此函数对null上的成员函数isAdmin()抛出错误
    调用。当我登录
    $this->roleService
    时,它返回
    null

任何人都可以解决这个问题?

为您的模型创建一个自定义访问器,并从中获取/设置值

public function getRoleServiceAttribute ()
{
    if(is_null($this->roleService)){
        $this->roleService = resolve(RoleService::class);
    }

    return $this->roleService;
}
然后您可以通过
$this->role\u service


另外,请确保将
$roleService
类属性声明为受保护,以避免从其他任何地方意外访问
$this->roleService

感谢您的帮助。我刚刚引用了一位专家的答案。他说我们不应该在
模型
类中进行依赖注入,因为它会破坏项目结构。项目应遵循以下结构:
控制器
->
服务
->
存储库
->
模型
->
数据库
。因此,我将按照它重构我的代码

它不起作用。返回了对null上的成员函数find()的调用
错误。您可以通过User::find(1)->roleService访问它吗?不,它返回
null
值。我已经更新了我的答案,检查它是否对您有效。它不起作用。它抛出一个错误
未定义的属性:App\Models\User::$roleService
您是否声明了
受保护的$roleService构造函数之前的变量?你不认为你的构造函数应该是这样的吗?
public function\uu构造(User$User)
然后
$this->roleService=$User?+我试图声明
$roleService
,但它不起作用。我认为这没关系,因为我已经尝试在其他类中删除它,并且它工作正常如果我将构造函数修改为
public function\u-construct(User$User)
,它可能会抛出错误,因为模型父类的构造函数是用一个参数初始化的,像这样的
\u-construct(array$attributes=array())
你能在isAdmin()和\uu-construct()中添加这个
dd($this->->roleService)
\uu construct()
中使用返回的
RoleService
类实例,但在
isAdmin()
中使用返回的
null
很好,您已经解决了它,您能用重构的代码更新您的答案吗?
    public function isAdmin() {
        return $this->roleService->isAdmin($this->role_id);
    }
public function getRoleServiceAttribute ()
{
    if(is_null($this->roleService)){
        $this->roleService = resolve(RoleService::class);
    }

    return $this->roleService;
}