使用laravel系統(tǒng)已經(jīng)為我們建立的前臺登錄模板磨澡,在此基礎(chǔ)上我們可以建立自己的后臺登錄模塊剩瓶!來看看詳細步驟缰冤。
- 開發(fā)環(huán)境:laravel5.7 largon集成開發(fā)環(huán)境
- 后臺模板:WeAdmin(LayUI)
一关贵、項目基礎(chǔ)搭建
- 啟動largon 打開終端命令
laravel new orange
新建一個項目
下載weAdmin后臺模板辛萍,并將靜態(tài)資源復(fù)制到項目的public目錄下悯姊,html文件復(fù)制到resources/view 目錄下。
二贩毕、數(shù)據(jù)庫的配置
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=orange
DB_USERNAME=root
DB_PASSWORD=123
三悯许、將laravel自帶注冊登錄運行起來
1、終端執(zhí)行命令:php artisan make:auth
生成用戶認證所需的路由和模板辉阶。此時查看web.php發(fā)現(xiàn)路由已更新先壕。
2、 接下來我們執(zhí)行遷移命令:php artisan migrate
生成數(shù)據(jù)表谆甜,然后在數(shù)據(jù)庫中你刷新一下就會發(fā)現(xiàn)多了幾張表垃僚。
3、再去刷新瀏覽器规辱,頁面的右上角多了登錄和注冊按鈕谆棺,我們隨即注冊一個用戶 user,注冊成功跳轉(zhuǎn)到首頁。此時數(shù)據(jù)庫中已插入一條數(shù)據(jù)罕袋。
4改淑、接下來我們可以使用這個賬號去登錄了,由于Laravel默認的登錄是使用郵箱的浴讯,我能體驗簡單的注冊登錄功能朵夏!
四、后臺admin登錄功能的實現(xiàn)榆纽。
1仰猖、創(chuàng)建管理員(admins)數(shù)據(jù)表
(1) 生成admins表的遷移文件:php artisan make:migration create_admins_table
,
(2) 修改 database/migrations/*_create_admins_table.php
中的 up()方法,如:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAdminsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
//php artisan make:migration create_users_table
//php artisan migrate
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->integer('mobile')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('admins');
}
}
- 終端執(zhí)行
php artisan migrate
, 我們的數(shù)據(jù)庫會自動添加admins表,手動往數(shù)據(jù)表admins里面添加一條數(shù)據(jù)捏肢。即將剛才前端注冊的數(shù)據(jù)插入數(shù)據(jù)表中,數(shù)據(jù)庫中密碼已經(jīng)加密饥侵,真是密碼不要忘記鸵赫。 - 記得修改下剛建立的數(shù)據(jù)庫表的字段長度!
(3) 生成數(shù)據(jù)表模型:php artisan make:model Models/Admin
,并修改app/Models/Admin.php
為:
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
- 為我們的后臺注冊用戶注冊登錄路由
Route::prefix('admin')->namespace('Admin')->group(function () {
//后臺首頁
$this->get('login', 'LoginController@showLoginForm')->name('admin.login');
$this->post('login', 'LoginController@login');
$this->post('logout', 'LoginController@logout')->name('admin.logout');
});
- 新建管理員登錄控制器:
php artisan make:controller Admin/LoginController
,添加代碼如下(參考auth/LoginController):
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* @var string
*/
protected $redirectTo = '/admin';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest:admin')->except('logout');
}
public function showLoginForm()
{
return view('admin.login');
}
protected function guard()
{
return auth()->guard('admin');
}
/**
* 后臺管理員退出跳轉(zhuǎn)到后臺登錄頁面
* Log the user out of the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
return redirect('/admin/login');
}
protected function attemptLogin(Request $request)
{
$username = $request->input('username');
$password = $request->input('password');
// 驗證用戶名登錄方式
$usernameLogin = $this->guard()->attempt(
['name' => $username, 'password' => $password], $request->has('remember')
);
if ($usernameLogin) {
return true;
}
// 驗證手機號登錄方式
$mobileLogin = $this->guard()->attempt(
['mobile' => $username, 'password' => $password], $request->has('remember')
);
if ($mobileLogin) {
return true;
}
// 驗證郵箱登錄方式
$emailLogin = $this->guard()->attempt(
['email' => $username, 'password' => $password], $request->has('remember')
);
if ($emailLogin) {
return true;
}
return false;
}
protected function validateLogin(Request $request)
{
$request->validate([
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
public function username()
{
return 'username';
}
}
- 添加管理員認證爆捞,修改
config/auth.php
文件奉瘤,如:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
]
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
- 創(chuàng)建admin登錄所用的中間件
通過命令:php artisan make:middleware AdminAuthMiddleware
創(chuàng)建后臺管理員中間件勾拉,并添加代碼如下:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class AdminAuthMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
//當 auth 中間件判定某個用戶未認證煮甥,會返回一個 JSON 401 響應(yīng),或者藕赞,如果不是 Ajax 請求的話成肘,將用戶重定向到 login 命名路由(也就是登錄頁面)。
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('admin/login');
}
}
return $next($request);
}
}
接下來去app\Http\Kernel.php protected $routeMiddleware
里面注冊該中間件
'auth.admin' => \App\Http\Middleware\AdminAuthMiddleware::class,
然后在后臺并在web.php中使用此中間件斧蜕,添加后臺中間件
Route::prefix('admin')->namespace('Admin')->group(function () {
//后臺首頁
$this->get('login', 'LoginController@showLoginForm')->name('admin.login');
$this->post('login', 'LoginController@login');
$this->post('logout', 'LoginController@logout')->name('admin.logout');
Route::middleware('auth.admin:admin')->name('admin.')->group(function () {
Route::get('/', 'HomeController@index');
});
});
- 創(chuàng)建后臺首頁控制器
此時我們的Admin\HomeController
并未創(chuàng)建
創(chuàng)建后臺首頁路由
php artisan make:controller Admin/HomeController
增加一條路由規(guī)則双霍,加載我們的后臺首頁
public function index()
{
// dd('后臺首頁,當前管理員:' . auth('admin')->user()->name);
return view('admin.index');
}
- 創(chuàng)建后臺首頁與login注冊界面(注意修改css js路徑)
views準備好后臺登錄頁面和后臺首頁頁面
后臺登錄頁面(注意此處ajax后臺登錄失敗錯誤信息的回顯方式)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>管理員登錄-WeAdmin Frame型后臺管理系統(tǒng)-WeAdmin 1.0</title>
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" href="/static/css/font.css">
<link rel="stylesheet" href="/static/css/weadmin.css">
<script src="/lib/layui/layui.js" charset="utf-8"></script>
</head>
<body class="login-bg">
<div class="login">
<div class="message">WeAdmin 1.0-管理登錄</div>
<div id="darkbannerwrap"></div>
<form method="post" class="layui-form" >
@csrf
<input name="username" placeholder="用戶名" type="text" lay-verify="required" class="layui-input" >
<hr class="hr15">
<input name="password" lay-verify="required" placeholder="密碼" type="password" class="layui-input">
<hr class="hr15">
<input class="loginin" value="登錄" lay-submit lay-filter="login" style="width:100%;" type="submit">
{{--<hr class="hr20" >--}}
{{--<div>--}}
{{--前端靜態(tài)展示批销,請隨意輸入洒闸,即可登錄。--}}
{{--</div>--}}
</form>
</div>
<script src="/js/jquery.js" charset="utf-8"></script>
<script type="text/javascript">
layui.extend({
admin: '{/}/static/js/admin'
});
layui.use(['form','admin'], function(){
var form = layui.form
,admin = layui.admin;
// layer.msg('玩命賣萌中', function(){
// //關(guān)閉后的操作
// });
//監(jiān)聽提交
form.on('submit(login)', function(data){
var data=data.field;
console.log(data);
$.ajax({
type: 'POST',
url: "/admin/login",
data:data,
success: function (data) {
localStorage.setItem("login",true);
location.href='/admin'
},
error: function (data) {
var error_msg=JSON.parse(data.responseText).errors;
layer.msg(error_msg.username[0],function(){
// location.href='/index.html'
});
},
})
// layer.msg(JSON.stringify(data.field),function(){
// // location.href='/index.html'
// });
return false;
});
});
</script>
<!-- 底部結(jié)束 -->
</body>
</html>
后臺首頁(注意此處后臺登錄模塊右上角登錄名的回顯方式)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>后臺管理-WeAdmin Frame型后臺管理系統(tǒng)-WeAdmin 1.0</title>
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link rel="shortcut icon" href="./favicon.ico" type="image/x-icon" />
<link rel="stylesheet" href="./static/css/font.css">
<link rel="stylesheet" href="./static/css/weadmin.css">
<script type="text/javascript" src="./lib/layui/layui.js" charset="utf-8"></script>
</head>
<body>
<!-- 頂部開始 -->
<div class="container">
<div class="logo">
<a href="./index.html">WeAdmin v1.0</a>
</div>
<div class="left_open">
<i title="展開左側(cè)欄" class="iconfont"></i>
</div>
<ul class="layui-nav left fast-add" lay-filter="">
<li class="layui-nav-item">
<a href="javascript:;">+新增</a>
<dl class="layui-nav-child">
<!-- 二級菜單 -->
<dd>
<a onclick="WeAdminShow('資訊','https://www.youfa365.com/')"><i class="iconfont"></i>資訊</a>
</dd>
<dd>
<a onclick="WeAdminShow('圖片','http://www.baidu.com')"><i class="iconfont"></i>圖片</a>
</dd>
<dd>
<a onclick="WeAdminShow('用戶','https://www.youfa365.com/')"><i class="iconfont"></i>用戶</a>
</dd>
</dl>
</li>
</ul>
<ul class="layui-nav right" lay-filter="">
<li class="layui-nav-item">
<a href="javascript:;">{{Auth::guard('admin')->user()->name}}</a>
<dl class="layui-nav-child">
<!-- 二級菜單 -->
<dd>
<a onclick="WeAdminShow('個人信息','http://www.baidu.com')">個人信息</a>
</dd>
<dd>
<a onclick="WeAdminShow('切換帳號','./login.html')">切換帳號</a>
</dd>
<dd>
{{--<a class="loginout" href="/admin/logout">退出</a>--}}
<a class="loginout" href="{{ route('admin.logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
退出
</a>
<form id="logout-form" action="{{ route('admin.logout') }}" method="POST" style="display: none;">
@csrf
</form>
</dd>
</dl>
</li>
<li class="layui-nav-item to-index">
<a href="/">前臺首頁</a>
</li>
</ul>
</div>
<!-- 頂部結(jié)束 -->
<!-- 中部開始 -->
<!-- 左側(cè)菜單開始 -->
<div class="left-nav">
<div id="side-nav">
<ul id="nav">
<li>
<a href="javascript:;">
<i class="iconfont"></i>
<cite>會員管理</cite>
<i class="iconfont nav_right"></i>
</a>
<ul class="sub-menu">
<li>
<a _href="./pages/member/list.html">
<i class="iconfont"></i>
<cite>會員列表</cite>
</a>
</li>
<li>
<a _href="./pages/member/del.html">
<i class="iconfont"></i>
<cite>會員刪除</cite>
</a>
</li>
<li>
<a href="javascript:;">
<i class="iconfont"></i>
<cite>會員管理</cite>
<i class="iconfont nav_right"></i>
</a>
<ul class="sub-menu">
<li>
<a _href="./pages/member/addInput.html">
<i class="iconfont"></i>
<cite>輸入框操作</cite>
</a>
</li>
<li>
<a _href="./pages/404.html">
<i class="iconfont"></i>
<cite>三級菜單演示</cite>
</a>
</li>
<li>
<a _href="./pages/404.html">
<i class="iconfont"></i>
<cite>導(dǎo)航菜單演示</cite>
</a>
</li>
</ul>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="iconfont"></i>
<cite>文章管理</cite>
<i class="iconfont nav_right"></i>
</a>
<ul class="sub-menu">
<li>
<a _href="./pages/article/list.html">
<i class="iconfont"></i>
<cite>文章列表</cite>
</a>
</li>
<li>
<a _href="./pages/article/category.html">
<i class="iconfont"></i>
<cite>分類管理</cite>
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="iconfont"></i>
<cite>訂單管理</cite>
<i class="iconfont nav_right"></i>
</a>
<ul class="sub-menu">
<li>
<a _href="./pages/order/list.html">
<i class="iconfont"></i>
<cite>訂單列表</cite>
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="iconfont"></i>
<cite>管理員管理</cite>
<i class="iconfont nav_right"></i>
</a>
<ul class="sub-menu">
<li>
<a _href="./pages/admin/list.html">
<i class="iconfont"></i>
<cite>管理員列表</cite>
</a>
</li>
<li>
<a _href="./pages/admin/role.html">
<i class="iconfont"></i>
<cite>角色管理</cite>
</a>
</li>
<li>
<a _href="./pages/admin/cate.html">
<i class="iconfont"></i>
<cite>權(quán)限分類</cite>
</a>
</li>
<li>
<a _href="./pages/admin/rule.html">
<i class="iconfont"></i>
<cite>權(quán)限管理</cite>
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="iconfont"></i>
<cite>系統(tǒng)統(tǒng)計</cite>
<i class="iconfont nav_right"></i>
</a>
<ul class="sub-menu">
<li>
<a _href="./pages/echarts/echarts1.html">
<i class="iconfont"></i>
<cite>拆線圖</cite>
</a>
</li>
<li>
<a _href="./pages/echarts/echarts2.html">
<i class="iconfont"></i>
<cite>柱狀圖</cite>
</a>
</li>
<li>
<a _href="./pages/echarts/echarts3.html">
<i class="iconfont"></i>
<cite>地圖</cite>
</a>
</li>
<li>
<a _href="./pages/echarts/echarts4.html">
<i class="iconfont"></i>
<cite>餅圖</cite>
</a>
</li>
<li>
<a _href="./pages/echarts/echarts5.html">
<i class="iconfont"></i>
<cite>雷達圖</cite>
</a>
</li>
<li>
<a _href="./pages/echarts/echarts6.html">
<i class="iconfont"></i>
<cite>k線圖</cite>
</a>
</li>
<li>
<a _href="./pages/echarts/echarts7.html">
<i class="iconfont"></i>
<cite>熱力圖</cite>
</a>
</li>
<li>
<a _href="./pages/echarts/echarts8.html">
<i class="iconfont"></i>
<cite>儀表圖</cite>
</a>
</li>
<li>
<a _href="./pages/echarts/echarts9.html">
<i class="iconfont"></i>
<cite>地圖DIY實例</cite>
</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- <div class="x-slide_left"></div> -->
<!-- 左側(cè)菜單結(jié)束 -->
<!-- 右側(cè)主體開始 -->
<div class="page-content">
<div class="layui-tab tab" lay-filter="wenav_tab" id="WeTabTip" lay-allowclose="true">
<ul class="layui-tab-title" id="tabName">
<li>我的桌面</li>
</ul>
<div class="layui-tab-content">
<div class="layui-tab-item layui-show">
{{--<iframe src='./pages/welcome.html' frameborder="0" scrolling="yes" class="weIframe"></iframe>--}}
</div>
</div>
</div>
</div>
<div class="page-content-bg"></div>
<!-- 右側(cè)主體結(jié)束 -->
<!-- 中部結(jié)束 -->
<!-- 底部開始 -->
<div class="footer">
<div class="copyright">Copyright ?2018 WeAdmin v1.0 All Rights Reserved</div>
</div>
<!-- 底部結(jié)束 -->
<script type="text/javascript">
// layui擴展模塊的兩種加載方式-示例
// layui.extend({
// admin: '{/}../../static/js/admin' // {/}的意思即代表采用自有路徑均芽,即不跟隨 base 路徑
// });
// //使用拓展模塊
// layui.use('admin', function(){
// var admin = layui.admin;
// });
layui.config({
base: './static/js/'
,version: '101100'
}).use('admin');
layui.use(['jquery','admin'], function(){
var $ = layui.jquery;
$(function(){
var login = JSON.parse(localStorage.getItem("login"));
if(login){
if(login=0){
window.location.href='/admin/login';
return false;
}else{
return false;
}
}else{
window.location.href='/admin/login';
return false;
}
});
});
</script>
</body>
<!--Tab菜單右鍵彈出菜單-->
<ul class="rightMenu" id="rightMenu">
<li data-type="fresh">刷新</li>
<li data-type="current">關(guān)閉當前</li>
<li data-type="other">關(guān)閉其它</li>
<li data-type="all">關(guān)閉所有</li>
</ul>
</html>
自此后天前臺用戶多用戶登錄完成丘逸!