1 添加路由
//注冊
Route::get('/register',"RegisterController@index");
Route::post('/register',"RegisterController@register");
//登錄
Route::get('/login',"LoginController@index");
Route::post('/login',"LoginController@login");
Route::get('/logout',"LoginController@logout");
2. 配置app下的默認守衛為 web 服務提供者為users
對應的model為新建的
App\Models\User::class
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
3 新建app\Models文件夾 Usermodel 繼承 Authenticatable
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $table = "users";
public $primaryKey = 'id';
protected $fillable = [
'name', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
4 建立控制和模板
LoginController.php
<?php
namespace App\Http\Controllers;
use App\Constants\ErrorCode;
use Brady\Tool\Data\Deal;
use Brady\Tool\Exception\ExceptionResult;
use Brady\Tool\Response\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
class LoginController extends Controller
{
public function index()
{
return view('login/index');
}
public function login(Request $request)
{
$data = $request->input();
$data = Deal::trim($data);
$name = $data['name'];
$password = $data['password'];
try{
if(empty($name)){
ExceptionResult::throwException(ErrorCode::USER_NOT_EMPTY);
}
if(empty($password)){
ExceptionResult::throwException(ErrorCode::PASSWORD_NOT_EMPTY);
}
$is_remeber = boolval(isset($data['is_remember']));
if(Auth::attempt(['name'=>$name,'password'=>$password],$is_remeber)) {
return redirect('/posts');
} else {
ExceptionResult::throwException(ErrorCode::LOGIN_FAILED);
}
} catch (ExceptionResult $e){
return Redirect::back()->with('error', $e->getMessage())->withInput();
}
}
public function logout()
{
Auth::logout();
return redirect('/login');
}
}
RegisterController.php
<?php
namespace App\Http\Controllers;
use App\Constants\ErrorCode;
use Brady\Tool\Exception\ExceptionResult;
use Brady\Tool\Response\Response;
use Illuminate\Http\Request;
use App\Models\User;
class RegisterController extends Controller
{
public function index()
{
return view('register/index');
}
public function register(Request $request)
{
try{
$data = $request->input();
if(empty($data['name'])){
ExceptionResult::throwException(ErrorCode::USER_NOT_EMPTY);
}
if(empty($data['password'])){
ExceptionResult::throwException(ErrorCode::PASSWORD_NOT_EMPTY);
}
if(empty($data['password_confirmation'])){
ExceptionResult:throwException(ErrorCode::PASSWORD_RE_NOT_EMPTY);
}
if($data['password'] != $data['password_confirmation']){
ExceptionResult::throwException(ErrorCode::PASSWORD_RE_NOT_SAME);
}
$user = new User();
$userExists = $user->where('name',$data['name'])->first();
if(!empty($userExists)){
ExceptionResult::throwException(ErrorCode::USER_EXISTS);
}
$user->name = $data['name'];
$user->password = bcrypt($data['password']);
$user->save();
Response::success($user);
} catch (ExceptionResult $e){
Response::error($e->getCode(),$e->getMessage());
}
}
}
登錄模板 index.blade.php
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3個meta標簽*必須*放在最前面,任何其他內容都*必須*跟隨其后! -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>登陸</title>
<!-- Bootstrap core CSS -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link href="http://v3.bootcss.com/assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="http://v3.bootcss.com/examples/signin/signin.css" rel="stylesheet">
<script src="/lib/jquery/jquery-2.2.1.js"></script>
<script src="/lib/layer/layer.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.0"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container" id="app">
<form class="form-signin" method="POST" action="/login">
{{csrf_field()}}
<h2 class="form-signin-heading">請登錄</h2>
<label for="inputName" class="sr-only">用戶名</label>
<input v-model="form.name" autocomplete="off" type="text" value="{{ old("name") }}" name="name" id="inputName" class="form-control" placeholder="用戶民" autofocus>
<label for="inputPassword" class="sr-only">密碼</label>
<input v-model="form.password" autocomplete="off" type="password" value="{{ old('password') }}" name="password" id="inputPassword" class="form-control" placeholder="密碼" >
<div class="checkbox">
<label>
<input v-model="form.is_remember" type="checkbox" value="{{ old('is_remember') }}" name="is_remember"> 記住我
</label>
</div>
@if (session('error'))
<div class="alert alert-danger">
{{ session('error') }}
</div>
@endif
<button class="btn btn-lg btn-primary btn-block" type="submit" id="login">登陸</button>
<a href="/register" class="btn btn-lg btn-primary btn-block" type="submit">去注冊>></a>
</form>
</div> <!-- /container -->
<script>
// var app = new Vue({
// el: '#app',
// data: {
// form:{
// name:'',
// password:'',
// _token:'',
// is_remember:0
// }
// },
// methods:{
// login:function(){
// this.form._token = $("#_token").val()
// axios.post('/login', this.form)
// .then(function (response) {
// var res = response.data;
// if(res.code != 200){
// layer.msg(res.msg,{icon:2});
// console.log(res.msg )
// return
// } else {
// layer.msg("登錄成功",{icon:1});
// setTimeout("location.href='/posts'",2000);
// }
// })
// .catch(function (error) {
// console.log(error);
// });
// }
// }
// })
</script>
</body>
</html>
注冊 index.blade.php
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3個meta標簽*必須*放在最前面,任何其他內容都*必須*跟隨其后! -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>注冊</title>
<!-- Bootstrap core CSS -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<link href="http://v3.bootcss.com/assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="http://v3.bootcss.com/examples/signin/signin.css" rel="stylesheet">
<script src="/lib/jquery/jquery-2.2.1.js"></script>
<script src="/lib/layer/layer.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.0"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container" id="app">
<div class="form-signin" >
<input type="hidden" id="_token" name="_token" value="{{csrf_token()}}">
<h2 class="form-signin-heading">請注冊</h2>
<div>
<label for="name" class="sr-only">用戶名</label>
<input v-model="form.name" type="text" name="name" id="name" class="form-control" autocomplete="off" placeholder="用戶名" autofocus style="margin-bottom:10px;">
<label class="sr-only">密碼</label>
<input v-model="form.password" type="password" name="password" id="inputPassword" autocomplete="off" class="form-control" placeholder="輸入密碼" >
<label class="sr-only" >重復密碼</label>
<input v-model="form.password_confirmation" type="password" name="password_confirmation" class="form-control" placeholder="重復輸入密碼" >
<button class="btn btn-lg btn-primary btn-block" type="submit" @click="registor">注冊</button>
</div>
</div>
</div> <!-- /container -->
<script>
var app = new Vue({
el: '#app',
data: {
form:{
name:'',
password:'',
password_confirmation:'',
_token:''
}
},
methods:{
registor:function(){
this.form._token = $("#_token").val()
axios.post('/register', this.form)
.then(function (response) {
var res = response.data;
if(res.code != 200){
layer.msg(res.msg,{icon:2});
console.log(res.msg )
return
} else {
layer.msg("注冊成功",{icon:1});
setTimeout("location.href='/login'",2000);
}
})
.catch(function (error) {
console.log(error);
});
}
}
})
</script>
</body>
</html>
