我正在尝试验证Laravel 5.2中的登录/注册系统。
我正在使用welcome.blade.php
作为索引页面,其中包含两个用于注册和登录的表单
这就是UserController.php
的设置方式:
namespace authme\Http\Controllers;
use Illuminate\Http\Request;
use authme\User;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
public function getDashboard()
{
return view('dashboard');
}
public function doSignUp(Request $request)
{
$this->validate($request, [
'email' => 'required|email|unique:users',
'first_name' => 'required|max:120',
'password' => 'required|min:6'
]);
$email = $request['email'];
$password = bcrypt($request['password']);
$first_name = $request['first_name'];
$last_name = $request['last_name'];
$location = $request['location'];
$phone = $request['phone'];
$user = new User();
$user->email = $email;
$user->password = $password;
$user->firstname = $first_name;
$user->lastname = $last_name;
$user->location = $location;
$user->phone = $phone;
$user->save();
Auth::login($user);
return redirect()->route('dashboard');
}
public function doSignIn(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required'
]);
if(Auth::attempt(['email' => $request['email'], 'password' => $request['password']])){
return redirect()->route('dashboard');
}
return redirect()->back();
}
}
要在注册/登录期间显示错误,请在我的视图文件(welcome.blade.php
)中添加:
@if(count($errors) > 0)
<div class="row">
<div class="alert alert-danger">
<ul>
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
</div>
@endif
并且路由设置如下:
Route::group(['middleware' => ['web']], function() {
Route::get('/', function () {
return view('welcome');
});
Route::post('/signup', [
'uses' => 'UserController@doSignUp',
'as' => 'signup'
]);
Route::post('/signin', [
'uses' => 'UserController@doSignIn',
'as' => 'signin'
]);
Route::get('/dashboard', [
'uses' => 'UserController@getDashboard',
'as' => 'dashboard'
]);
});
输入正确的详细信息时,表单正常工作。但是,当我输入错误数据时:
但是,我在代码中找不到任何可能的语法错误。有任何逻辑错误吗?
PS:
答案 0 :(得分:5)
答案 1 :(得分:1)
您还可以使用以下代码显示使用无效凭据登录的错误。
public function doSignIn(Request $request)
{
$rules = array(
'email' => 'required',
'password' => 'required'
);
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()){
return redirect('welcome')
->withErrors($validator)
->withInput();
}else{
if(Auth::attempt(['email' => $request['email'], 'password' => $request['password']])){
return redirect()->route('dashboard');
}
}
}
答案 2 :(得分:0)
在我看来,您的验证错误消息未保存到会话中。看看这个。