簡體   English   中英

Laravel奇怪的錯誤:雄辯的模型更改為Builder類的實例

[英]Laravel strange error: Eloquent model changes into an instance of Builder class

我正在使用laravel 4.2。 我有這個奇怪的錯誤。

所有我想要做的就是這個對象傳遞UserEloquent模型)的方法scopeSendToEmailVerification模型; 並遇到了這個我不知道的奇怪錯誤。

這是我的代碼:

class EmailVerification extends Eloquent
{
    ...
    public function scopeSendTo(User $user, $type)
    {
        $token = Str::slug(microtime(true).Hash::make(Str::random(20)));

        $verification = new EmailVerification([
            'token' => $token,
            'type' => $type,
        ]);

        $user->verifications()->save($verification);

        Mail::send('emails.verification', ['verification' => $verification], function ($message) {

            $name = $user->profile ? $user->profile->first_name : '';

            $message->to($user->email, $name)->subject('Account Verification');

        });
        ...
    }
    ...
}

我正在嘗試使用這種方法:

$user = User::find($userId);

EmailVerification::sendTo($user, 'signup');

但這會引發此錯誤:

在此處輸入圖片說明

我什至嘗試做dd(get_class($user))來確認傳遞的對象是User對象,嚴格來說不是Illuminate\\Database\\Eloquent\\Builder的實例; 但我不知道這是什么問題。

查詢范圍對於重用模型中的查詢邏輯很有幫助。 這意味着傳遞給scope方法的第一個參數是查詢生成器實例,可以對其進行操作和返回以允許方法鏈接。 在您的情況下,范圍方法定義應如下所示:

public function scopeSendTo($query, User $user, $type)
{
    // code goes here
}

盡管上面的代碼可以工作,但這是一種不好的方法,因為這不是Eloquent模型范圍的預期目的。

我建議您修改解決此問題的策略。 該答案為使用Laravel的集成身份驗證服務實施電子郵件驗證提供了一些好的建議,或者您可以考慮使用功能更強大的身份驗證解決方案,例如Confide

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM