In Laravel-8, I am creating an end point for ForgotPassword and to also send notification to the user email:
public function forgotPassword(ResetPasswordRequest $request)
{
try {
$user = User::where('email', $request->email)->first();
if (!$user){
return $this->error('We can\'t find a user with that e-mail address.', 400);
}
$email = $request->email;
$token = Str::random(10);
$passwordReset = PasswordReset::updateOrCreate(
['email' => $user->email],
[
'email' => $email,
'token' => $token,
'created_at' => now()->addHours(10),
]
);
// Send Email Based on condition
if ($user && $passwordReset){
$user->notify(
new PasswordResetRequest($token)
);
}
return $this->success('We have e-mailed your password reset link!', [
'user' => $user,
]);
} catch(\Exception $e) {
Log::error($e);
return $this->error($e->getMessage(), $e->getCode());
}
}
As I submit, I got this error:
local.ERROR: LogicException: App\Models\User::token must return a relationship instance, but "null" was returned
When I removed:
if ($user && $passwordReset){
$user->notify(
new PasswordResetRequest($token)
);
}
Notification:
class PasswordResetRequest extends Notification
{
use Queueable;
protected $token;
public function __construct($token)
{
$this->token = $token;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
$url = url('http://localhost:4200/reset-password-submit?token='.$this->token);
return (new MailMessage)
->line('You are receiving this email because we received a password reset request for your account.')
->action('Reset Password', url($url))
->line('If you did not request a password reset, no further action is required.');
}
}
No error, and it was also inserted into the password_resets table. but I need to send notification.
User and PasswordReset models are not even related.
How do I get this resolved?
Thanks