how password reset in Flutter with API Laravel in Flutter
Limited Time Offer!
For Less Than the Cost of a Starbucks Coffee, Access All DevOpsSchool Videos on YouTube Unlimitedly.
Master DevOps, SRE, DevSecOps Skills!
I am resetting a password in Flutter with an API built with Laravel. This example assumes that you have already set up the necessary endpoints in your Laravel API and that you are using the Flutter http
package to make HTTP requests.
Flutter code for sending a password reset request:
Future<void> sendPasswordResetRequest(String email) async {
final url = 'http://your-api-url.com/password/reset';
final response = await http.post(
Uri.parse(url),
body: {'email': email},
);
if (response.statusCode == 200) {
// Password reset request sent successfully
} else {
throw Exception('Failed to send password reset request');
}
}
Laravel code for generating a password reset token:
Create a controller that will handle the password reset logic. You can use the php artisan make:controller Auth\ForgotPasswordController
command to create the controller.
public function sendPasswordResetEmail(Request $request)
{
$request->validate(['email' => 'required|email']);
$user = User::where('email', $request->email)->first();
if (!$user) {
return response()->json(['message' => 'User not found'], 404);
}
$token = Str::random(60);
DB::table('password_resets')->insert([
'email' => $request->email,
'token' => Hash::make($token),
'created_at' => Carbon::now()
]);
Mail::to($request->email)->send(new PasswordResetMail($token));
return response()->json(['message' => 'Password reset email sent']);
}
Laravel code for verifying the password reset token and updating the password:
public function resetPassword(Request $request) { $request->validate([ 'token' => 'required', 'email' => 'required|email', 'password' => 'required|confirmed|min:8' ]); $reset = DB::table('password_resets') ->where('email', $request->email) ->where('token', $request->token) ->first(); if (!$reset) { return response()->json(['message' => 'Invalid password reset token'], 400); } $user = User::where('email', $request->email)->first(); if (!$user) { return response()->json(['message' => 'User not found'], 404); } $user->password = Hash::make($request->password); $user->save(); DB::table('password_resets')->where('email', $request->email)->delete(); return response()->json(['message' => 'Password reset successfully']); }