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为新建的
AppModelsUser::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' => AppModelsUser::class, ], // 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], ], 'passwords' => [ 'users' => [ 'provider' => 'users', 'table' => 'password_resets', 'expire' => 60, ], ], ];
3 新建appModels文件夹 Usermodel 继承 Authenticatable
<?php namespace AppModels; use IlluminateDatabaseEloquentModel; use IlluminateFoundationAuthUser 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 AppHttpControllers; use AppConstantsErrorCode; use BradyToolDataDeal; use BradyToolExceptionExceptionResult; use BradyToolResponseResponse; use IlluminateHttpRequest; use IlluminateSupportFacadesAuth; use IlluminateSupportFacadesRedirect; 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 AppHttpControllers; use AppConstantsErrorCode; use BradyToolExceptionExceptionResult; use BradyToolResponseResponse; use IlluminateHttpRequest; use AppModelsUser; 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>