1

I'm using laravel 4.2. And I have this strange error.

All I'm trying to do is pass this object of User (Eloquent model) to the method scopeSendTo of EmailVerification model; and came across this strange error which I can't figure out.

Here's my code:

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');

        });
        ...
    }
    ...
}

I'm trying to use this method like this:

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

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

But it throws this error:

enter image description here

I even tried doing dd(get_class($user)) which confirms that the object passed is an User object and strictly not an instance of Illuminate\Database\Eloquent\Builder; but I can't figure out what is the problem here.

kabirbaidhya
  • 3,264
  • 3
  • 34
  • 59

1 Answers1

1

Query Scopes are helpful for reusing query logic in models. This means that the first parameter that gets passed to the scope method is a query builder instance , which can be manipulated and returned to allow for method chaining. In your case the scope method definition should look like this:

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

While the code above will work, it's a bad approach, since that's not the intended purpose of scopes for Eloquent models.

I suggest revising your strategy for solving this problem. This answer gives some good advice on implementing email verification using Laravel's integrated authentication service, or you can consider using a more robust authentication solution such as Confide.

Community
  • 1
  • 1
Bogdan
  • 43,166
  • 12
  • 128
  • 129