以下是一个示例:*app/Http/Controllers/Auth/PasswordController.php:
<?php
namespace SundaySlim\Http\Controllers\Auth;
use SundaySlim\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
use ResetsPasswords;
public function __construct()
{
$this->redirectTo = route('backend.dashboard');
$this->middleware('guest');
}
protected function resetPassword($user, $password)
{
$user->password = $password;
$user->save();
auth()->login($user);
}
}
您可以看到,这里有一个resetPassword($user, $password)方法,它是从vendor/laravel/framework/src/Illuminate/Foundation/Auth/ResetPasswords.php中复制的。它被修改了,以便不再使用bcrypt加密密码。
以下是该方法原始代码:
protected function resetPassword($user, $password)
{
$user->password = bcrypt($password);
$user->save();
Auth::guard($this->getGuard())->login($user);
}
同时,可以看到 - Auth::guard($this->getGuard())->login($user); 已更改为 auth()->login($user);
主要思路是在 Users.php 模型中创建一个修改器,将密码加密为bcrypt码。
因此,以下是带有该修改器的模型User.php:
<?php
namespace SundaySlim;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value);
}
}
问题:
1. 为什么要在 Users.php 中创建一个改变器来bcrypt密码,而不是像默认情况下那样在 resetPassword($user,$password) 中进行?将bcrypt密码从 resetPassword($user,$password) 移动到User.php模型中的实际原因是什么?
2. auth()->login($user);和 Auth::guard($this->getGuard())->login($user);之间有什么区别?
顺便说一下,这是 routes.php 的内容:
Route::group(['middleware' => ['web']], function () {
Route::get('backend/dashboard', [
'uses'=>'Backend\DashboardController@index',
'as'=>'backend.dashboard'
]);
Route::controller('auth', 'Auth\AuthController', [
'getLogin' => 'auth.login',
'getLogout' => 'auth.logout'
]);
Route::controller('auth/password', 'Auth\PasswordController', [
'getEmail' => 'auth.password.email',
'getReset' => 'auth.password.reset'
]);
});
$user->password = 'something'; $user->save();
。如果存在mutator(属性修改器),那么在保存前用户模型中的密码将被加密。如果不存在mutator,那么该密码将以明文形式保存至数据库。 - Kryten