eskimo
eskimo

Reputation: 2624

Laravel pass object to method in model

In my User model I can do:

public function sendPasswordResetNotification($token)
{
  $message = (new UserForgotPassword($this->email, $this->name, $token));
}

but how can I pass the full User object?

public function sendPasswordResetNotification($token)
{
  $message = (new UserForgotPassword($user, $token));
}

Using $user doesn't work, while it does work in:

protected static function booted()
{
  static::creating(function ($user) {
    $user->uuid = Str::uuid();
  });
}

Upvotes: 0

Views: 910

Answers (2)

Abdel-aziz hassan
Abdel-aziz hassan

Reputation: 380

just use this instead,

$message = (new UserForgotPassword($this, $token));

Upvotes: 1

Prince Dorcis
Prince Dorcis

Reputation: 1045

Use $this to have access to the User instance inside the User model (in a non-static method).

public function sendPasswordResetNotification($token)
{
  $message = (new UserForgotPassword($this, $token));
}

Note: If your method was a static method, you would use static (or self) instead of $this.

Also, in the example you gave, $user is not actually a variable in the booted method. It is rather a parameter of the closure (the anonymous function) passed to the created method.

Upvotes: 0

Related Questions