How do I manually send a password reset request in Laravel 5.2?
In Laravel, the ResetsPasswords trait handles the intricate logic of generating tokens, emailing them, and managing expiration times. However, the standard flow relies on an HTTP POST request hitting a specific route defined by that trait. When you need to trigger this process from within your own application logicâperhaps for account recovery support or administrative tasksâyou face a common architectural hurdle: how to invoke the protected postEmail method without exposing it to a public URL or breaking the controller's dependency injection.
The core issue arises because PasswordController, which contains the postEmail method, is not a global singleton service like the database connection or cache manager. It is instantiated by Laravel's routing system based on the specific route definition and the controller namespace you are currently in. Attempting to instantiate it directly via new PasswordController() often results in runtime errors because the constructor relies on Laravel's container to resolve dependencies such as the user model, mailer, and the ResetsPasswords trait itself. These dependencies are typically bound in the application's service provider or automatically resolved when you extend a base controller.
To bypass this dependency injection barrier while staying within the bounds of Laravel 5.2, you must leverage the framework's own routing mechanisms rather than trying to manually instantiate the controller class. The most robust solution is to dispatch an event that your own route listener handles, or more simply, to trigger the underlying logic by sending a request to the password reset route programmatically using Route::action() or by utilizing the PasswordResetController if you have explicitly defined it in your application's routes.
However, if you are strictly adhering to Laravel 5.2 and want to avoid defining new routes for internal triggers, you can access the controller's logic through the App\Providers\RouteServiceProvider or by defining a helper method within your own controller that calls the reset logic directly using the underlying services. A cleaner approach in 5.2 involves creating a dedicated admin route that accepts a user ID and then uses the Password::sendResetLink() static method if available, or manually invoking the PostEmailController class instance after ensuring its dependencies are resolved.
Consider this implementation pattern where you define a custom controller action to handle the manual trigger:
// In your AdminController or similar
public function resetUser($id) {
$user = User::findOrFail($id);
// We need to ensure the PasswordController is instantiated correctly
// by resolving it through the container if possible, or using a specific helper.
// In Laravel 5.2, direct instantiation often fails due to trait dependencies.
// The safest way in 5.2 without defining new routes for internal calls:
// Use the underlying logic from the ResetsPasswords trait directly.
$user->sendPasswordResetNotification($this->tokenGenerator);
// Note: This assumes you have access to the token generation logic.
}
A more explicit method that aligns with how Laravel 5.2 structures these controllers is to define a specific route in your routes.php file that points directly to the PasswordController@postEmail action, but pass the target user ID as a parameter or store it in the session before calling the action. This mimics the external request flow without exposing the endpoint publicly if you scope it behind middleware.
Alternatively, you can manually construct the token and email content using the Mail facade and the Hasher utility, effectively replicating what postEmail does under the hood. This gives you granular control and avoids the dependency complexity of instantiating the controller class directly. You would generate a unique token, save it to the database with an expiry timestamp, and then dispatch the email using your configured mailer.
use Illuminate\Support\Facades\Mail;
use App\User;
public function resetPasswordManually(User $user) {
// Generate a secure token
$token = \Illuminate\Support\Str::random(40);
// Save to database with expiration
$user->forceFill([
'password_reset_token' => $token,
'password_reset_at' => date('Y-m-d H:i:s', strtotime('+1 day'))
])->save();
// Send the email using your Mail facade
Mail::send('emails.reset-password', ['token' => $token], function ($message) use ($user) {
$message->to($user->email)->subject('Password Reset');
});
}
This approach decouples you from the controller's internal state and ensures that your manual trigger works regardless of how the ResetsPasswords trait is implemented in your specific application version. It also makes it easier to audit who triggered the reset and when, by logging the action alongside the token creation.