In a recent project I’ve been building a Customer Service Portal where “agents” are allowed to perform certain actions on a user’s account. One of the required features was to send a password reset email to the user, and I managed to achieve this with a few lines of code, thanks to traits in Laravel.
The Illuminate\Foundation\Auth\ResetsPasswords
trait used in the PasswordController.php
file is a quick and easy way to re-use the functionality available in Laravel (the name and path of the trait will vary across different versions of Laravel). You can include this trait in any controller as shown in the below code (lines 7 and 16).
The Code
Because the trait expects a Request
object (instance of Illuminate\Http\Request
), we need to create a new instance and pass it into the trait’s sendResetLinkEmail
function. This can be achieved by creating a new Request (line 32), and the merging in the email address of the user (line 34).
The new $request
can then be passed as a parameter to the sendResetLinkEmail
function. If all done correctly, the user should receive an password reset email in their inbox.
Use Case
Why would anyone want to request a password reset outside of the usual flow? There could be many uses – one of which is the reason why I implemented the code in the first place: to allow customer service “agents” to trigger a password reset on the behalf of the user. This could be because the user doesn’t know how to trigger a password reset themselves.
It could have other uses too. For example, you may want to automatically trigger a password reset after three failed login attempts (and subsequently locking the account until a password reset is performed).
Leave a Comment
Did this tutorial help you? Have you used the functionality for a different use case? Need help with your own issue? Let me know in the comment section below.