【问题标题】:Laravel Use Eloquent model from custom UserServiceProviderLaravel 使用来自自定义 UserServiceProvider 的 Eloquent 模型
【发布时间】:2016-02-16 21:59:07
【问题描述】:

我是 Laravel 的新手,只是在玩弄它并重新开始使用 MVC。

我正在尝试将自己的用户身份验证提供程序(自定义密码哈希)作为在 Laravel 中实现 UserProviderInterface 的服务。

在 app/controllers/Account.php 内:

public function postCreate() {
    Auth::attempt(Input::all());
}

我的应用通过自定义提供程序类路由 Auth::attempt,并将表单中的 Input::all 传递给 retrieveByCredentials 方法。

在 app/services/PasswordHash/PasswordHashUserProvider.php 里面:

public function retrieveByCredentials(array $credentials) {
    // Why can't I do this?
    //Error: PasswordHash/User not found
    User::find($credentials['username']);

    dd($credentials);
}

此时我不知道如何从这个服务类中访问我的用户雄辩模型。我尝试了命名空间,但没有运气。

【问题讨论】:

  • 你试过use use App\User; 吗?
  • 是的,没用。我意识到我应该将一个空白用户模型传递给我的密码类并调用它的方法来创建我的用户模型。我现在可以通过用户名进行查询。

标签: php laravel eloquent


【解决方案1】:

服务提供者的启动方法使用服务容器来注入依赖。为此,您应该能够执行以下操作(不使用 Facades,但我不经常使用 Facades)。

class PasswordHashUserProvider extends ServiceProvider
{
    protected $user;

    public function boot(User $user)
    {
        $this->user = $user;
    }

}

然后您可以通过$this->user访问用户

来源:https://laravel.com/docs/master/providers#the-boot-method

【讨论】:

    猜你喜欢
    • 2018-09-16
    • 2020-12-11
    • 2023-04-01
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多