Joh*_*ohn 9 php authentication laravel
我正在尝试Laravel的Auth类,但每当我尝试登录用户时,该方法返回false.这是我的代码:
routes.php文件
Route::get('new-user', function() {
return View::make('register');
});
Route::post('new-user', function() {
$name = Input::get('name');
$email = Input::get('email');
$password = Hash::make(Input::get('password'));
$user = new User;
$user->name = $name;
$user->email = $email;
$user->password = $password;
$user->save();
});
Route::get('login', function() {
return View::make('login');
});
Route::post('login', function() {
$user = array(
'email' => Input::get('email'),
'password' => Hash::make(Input::get('password'))
);
if (Auth::attempt($user)) {
//return Redirect::intended('dashboard');
return "ok.";
} else {
return "Wrong.";
}
});
Run Code Online (Sandbox Code Playgroud)
意见/ login.blade.php
{{ Form::open(array('url' => 'login', 'method' => 'post')) }}
<h1>Login:</h1>
<p>
{{ Form::label('email', 'Email: ') }}
{{ Form::text('email') }}<br />
{{ Form::label('password', 'Password: ') }}
{{ Form::password('password') }}<br />
</p>
<p>
{{ Form::submit('Login') }}
</p>
{{ Form::close() }}
Run Code Online (Sandbox Code Playgroud)
配置/ auth.php
return array(
'driver' => 'eloquent',
'model' => 'User',
'table' => 'users',
'reminder' => array(
'email' => 'emails.auth.reminder', 'table' => 'password_reminders',
),
);
Run Code Online (Sandbox Code Playgroud)
数据库具有电子邮件和密码字段,密码字段为varchar(60).每当我将登录信息发送到/ login时,它都会返回"Wrong".我真的看不出这里有什么不对吗?
你的代码是错误的,因为你传递了错误的变量Auth::attempt().该方法需要一个包含密钥用户名,密码的数组,并可选择记住.鉴于此,您的上述代码应为:
Route::post('login', function()
{
$credentials = [
'username' => Input::get('email'),
'password' => Input::get('password')
];
dd(Auth::attempt($credentials));
});
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
此外,我将为您提供额外代码的片段,以改善您的工作流程.存储新用户的路线:
Route::post('register', function()
{
$input = Input::only(['username', 'email', 'password']);
// validate data
Eloquent::unguard();
$user = User::create($input);
Auth::loginUsingId($user->id);
return Redirect::to('dashboard');
});
Run Code Online (Sandbox Code Playgroud)
然后在您的用户模型中添加方法
public function setPasswordAttribute()
{
$this->password = Hash::make($this->password);
}
Run Code Online (Sandbox Code Playgroud)
这样,密码将在每次设置时自动散列
在尝试之前不要对密码进行哈希处理:
$user = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($user)) {
//return Redirect::intended('dashboard');
return "ok.";
} else {
return "Wrong.";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19120 次 |
| 最近记录: |