3

I have setup a password reset in Laravel. I have read through the docs https://laravel.com/docs/5.5/passwords but I cant see anywahere if there is a function to only allow the reset password for certain users based on a field in in the database in the users table.

In my users table I have added the field user_type if the user_type is set to 2 I dont want to allow password reset links being sent for that user

3 Answers 3

5

In Http/Controllers/Auth/ForgotPasswordController.php a trait SendsPasswordResetEmails is used.

You can override the function sendResetLinkEmail in the ForgotPasswordController and add your condition there.

public function sendResetLinkEmail(Request $request)
{
    $user = User::where('email', $request->get('email'))->get();
    if (!$user || $user->user_type == 2) {
       return redirect()->back()->with('error' => '...');
    }
    //rest of function
    $this->validateEmail($request);

    $response = $this->broker()->sendResetLink(
        $request->only('email')
    );

    return $response == Password::RESET_LINK_SENT
                ? $this->sendResetLinkResponse($response)
                : $this->sendResetLinkFailedResponse($request, $response);
}
3

Dimitri's Answer is great and correct. Thanks for it.

But there's a way to avoid code duplication: Instead of copying the original code, just call the trait's method when you're done with your custom code.

In your ForgotPasswordController, replace use SendsPasswordResetsEmails; with

use SendsPasswordResetEmails {
    // make the trait's method available as traitSendResetLinkEmail
    sendResetLinkEmail as public traitSendResetLinkEmail;
}

Then write sendResetLinkEmail as follows:

$this->validateEmail($request);    
$user = User::where('email', $request->get('email'))->get();
if (!$user || $user->user_type == 2) {
   return redirect()->back()->with('error' => '...');
}
// call the original method
return $this->traitSendResetLinkEmail($request);
0

Both answers helped with two modifications as follows,

  1. use first() instead of get() as the get method returns an array.

    $user = User::where('email', $request->get('email'))->get();

  2. change with to withErrors (don't forget to add missing [])

    return redirect()->back()->withErrors(['email' => '...']);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.