再寫登入的驗證及功能
今天我們要來做登入的判斷跟動作,
我們在HomeController.php引用
use Validator;
然後新增一個方法
function indexProcess(Request $request)
{
$input = $request->all();
//驗證規則
$rules = [
//帳號
'account' => [
'required',
],
//密碼
'password' => [
'required',
],
//勾選
'terms' => [
'accepted',
],
];
if($request->has(['terms']))
$input['terms'] = 1;
//驗證資料
$validator = Validator::make($input, $rules);
if($validator->fails())
{
//資料驗證錯誤
return redirect('/home/index')
->withInput($input)
->withErrors($validator);
}
if($input['account'] == 'admin' && $input['password'] == 'admin')
{
return redirect('/home/main');
}
else
{
$validator->errors()->add('account', '帳號或密碼錯誤');
//資料驗證錯誤
return redirect('/home/index')
->withInput($input)
->withErrors($validator);
}
}
登入頁改成這樣
resources/views/home/index.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登入</title>
<script src="http://cdn.bootcss.com/jquery/1.11.0/jquery.min.js" type="text/javascript"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="/css/app.css">
</head>
<body>
<form id="form1" method="post" action="">
<!-- 自動產生 csrf_token 隱藏欄位-->
{!! csrf_field() !!}
<div class="login_form">
<div class="login_title">登入</div>
<a href="/home/about" class="login_label">關於我們</a>
<div class="login_label">帳號</div>
<div class="login_textbox">
<input name="account" class="form_textbox" type="text" value="{{ old('account') }}" placeholder="請輸入帳號"/>
</div>
<div class="login_label">密碼</div>
<div class="login_textbox">
<input name="password" class="form_textbox" type="password" value="{{ old('password') }}" placeholder="請輸入密碼"/>
</div>
<div class="login_label">
<input name="terms" class="form-check-input" type="checkbox"
@if(old('terms') == 1)
checked
@endif
>
<span>我同意服務條款</span>
</div>
<div class="login_error">
<!-- 錯誤訊息模板元件 -->
@include('layout.ValidatorError')
</div>
<div class="btn_group">
<button type="submit" class="btn btn-success btn_login">登入</button>
</div>
</div>
</form>
</body>
<html>
然後新增一個首頁
resources/views/home/main.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>首頁</title>
<link rel="stylesheet" href="/css/app.css">
</head>
<body>
<h1>首頁</h1>
</body>
<html>
我們在原本的測試項目再新增一個方法,
確認密碼輸入錯誤的反應
BrowserUnitTest.php
public function test_login_page_login_error()
{
$this->visit('/home/index')
->type('admin', 'account')
->type('123456', 'password')
->check('terms')
->press('登入')
->seePageIs('/home/index');
}
首頁做完之後我們再來測試一下我們的成果
php artisan test
我們終於完成了階段性任務!