Home > Software design >  Laravel Passing Data To Middleware From Controller
Laravel Passing Data To Middleware From Controller

Time:11-19

I want to pass some parameters to an after middleware after the controller has finished running, this is in order to invalidate any password reset tokens if a new one is generated.

My code is:

Controller

public function resetPasswordRequest(Request $request) {

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

    if (!$user) {
        throw ValidationException::withMessages([
            'message' => 'invalid_email',
        ]);
    }

    $reset_request = Password_reset::create([
        'user_email' => $request['email'],
        'reset_token' => Helper::makeRandomString(8, true),
    ]);

    $reset_token = $reset_request['reset_token'];
    $user_email = $request['email'];
    /*
    Helper::sendEmail('pass_reset', $user_email = $request['email'], $reset_token);
    */

  
    return response(array('message' => 'success', 'email' => $user_email, 'reset_token' => $reset_token, 'type' => 'reset'), status:200);
}

//Middleware

public function handle(Request $request, Closure $next)
{

    $user_data = $next($request);

    error_log($user_data);


    $user_email = $user_data['email'];
    $type = $user_data['reset'];

    $tokens = null;

    if ($type == 'reset') {
        $tokens = Password_reset::where('user_email', '=', $user_email)->where('used', false)->get();
    } else if ($type == 'confirmation') {
        $tokens = EmailConfirm::where('user_email', '=', $user_email)->where('used', false)->get();
        error_log('fffff');
    }

    error_log('gggg');

    //Might not be optimum, need consultation

    foreach ($tokens as $column) {
        $column['used'] = true;
        $column->save();
    }

    return $next($request);
}

The problem comes with the fact that I do not seem to be able to find a way to pass this data, if I try to access it via the content method the result will be an array of chars.

Any tips on this or another solution I can use?

CodePudding user response:

You don't need middleware because resetting a password is almost never a protected resource.

How can you log in and go to a guarded resource if you forgot your password?

Middleware is to guard routes and its corresponding controllers.

In this case, there is a user, that is not logged in and wants to reset the password of its account.

Just process the request in the controller.

  • Related