Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Adding password confirmation on certain routes in Laravel

If you’ve used some well creafted web application, such as GitHub for instance, you might’ve noticed that upon saving sensitive information such as settings or payment details, it asks for the password confirmation before performing the action. This adds the extra layer of security and certainly a nice-to-have feature.

In Laravel v6.2.0, the very feature has been shipping in-built. You can add password confirmation on any route by attaching a password.confirm middleware to it and it will take care of rest of the things. i.e navigating the user to re-confirm their password. You can locate the middleware over here: src/Illuminate/Auth/Middleware/RequirePassword.php

Below is how you can use the middleware.

Route::get('/payment-details', 'PaymentsController@save')->middleware('password.confirm');

Now, If you attempt to access the route, you will be prompted to confirm your password.

The middleware also take care of the fact that user don’t have to re-confirm their password for the certain period of time by storing a timestamp in the user’s session that lasts for three hours by default when he/she reconfirms first time. You can also customize this duration using a new password_timeout configuration option in the in the auth.php config file like below.

return [
    //... code commented for brevity

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may specify the amount of seconds before a password confirmation
    | is timed out and the user's prompted to give their password again on the
    | confirmation screen. By default the timeout lasts for three hours.
    |
    */
    'password_timeout' => 10800,
];

All this can go on to work because Laravel has added a new password validation rule which can be used to validate the given password with the user’s actual password. You can also pass a guard name as a parameter.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?