若要编写自己的密码重置逻辑,您仍然可以使用开箱即用的默认迁移,也可以直接创建自己的密码重置逻辑。最重要的部分是令牌。由于您要自行重置密码,因此您需要做出以下几个决定:
您将需要在同一控制器中提供 2 个页面、4 个不同的路由和 4 个不同的功能。“我忘记了密码”页面和“重置密码”页面。在第一页中,显示一个表单,您可以在其中获取用户电子邮件。并发布到以下控制器。
//to be added on top as use statements
use DB;
use Auth;
use Hash;
use Carbon;
use App\User;
public function sendPasswordResetToken(Request $request)
{
$user = User::where ('email', $request->email)-first();
if ( !$user ) return redirect()->back()->withErrors(['error' => '404']);
//create a new token to be sent to the user.
DB::table('password_resets')->insert([
'email' => $request->email,
'token' => str_random(60), //change 60 to any length you want
'created_at' => Carbon::now()
]);
$tokenData = DB::table('password_resets')
->where('email', $request->email)->first();
$token = $tokenData->token;
$email = $request->email; // or $email = $tokenData->email;
/**
* Send email to the email above with a link to your password reset
* something like url('password-reset/' . $token)
* Sending email varies according to your Laravel version. Very easy to implement
*/
}
第二部分,当用户点击链接时
/**
* Assuming the URL looks like this
* http://localhost/password-reset/random-string-here
* You check if the user and the token exist and display a page
*/
public function showPasswordResetForm($token)
{
$tokenData = DB::table('password_resets')
->where('token', $token)->first();
if ( !$tokenData ) return redirect()->to('home'); //redirect them anywhere you want if the token does not exist.
return view('passwords.show');
}
显示一个包含 2 个输入的表单的页面 - 新密码或所需的内容 - 新密码确认或所需的任何内容 表单应发布到映射到以下控制器的同一 URL。为什么?因为我们仍然需要使用令牌来查找实际用户。password
password_confirm
public function resetPassword(Request $request, $token)
{
//some validation
...
$password = $request->password;
$tokenData = DB::table('password_resets')
->where('token', $token)->first();
$user = User::where('email', $tokenData->email)->first();
if ( !$user ) return redirect()->to('home'); //or wherever you want
$user->password = Hash::make($password);
$user->update(); //or $user->save();
//do we log the user directly or let them login and try their password for the first time ? if yes
Auth::login($user);
// If the user shouldn't reuse the token later, delete the token
DB::table('password_resets')->where('email', $user->email')->delete();
//redirect where we want according to whether they are logged in or not.
}
不要忘记添加路线
Route::get('password-reset', 'PasswordController@showForm'); //I did not create this controller. it simply displays a view with a form to take the email
Route::post('password-reset', 'PasswordController@sendPasswordResetToken');
Route::get('reset-password/{token}', 'PasswordController@showPasswordResetForm');
Route::post('reset-password/{token}', 'PasswordController@resetPassword');
注意:可能存在拼写错误或语法错误,因为我没有对此进行测试,而是直接从头顶上写在这里。如果您看到错误/异常,请不要惊慌,请阅读错误并搜索Google。