一.相关代码:
(1)login.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="/static/plugins/layui/css/layui.css">
<script type="text/javascript" src="/static/plugins/layui/layui.js"></script>
<title>后台登录</title>
</head>
<body style="background-color: #1E9FFF;">
<div style="position:absolute;left:50%;width:480px;top:50%;margin-left:-240px;
background:#fff;margin-top:-200px;padding:20px;border-radius:4px;box-shadow:5px 5px 20px #444;">
<div class="layui-form">
@csrf
<div class="layui-form-item" style="text-align: center;color:blue;font-weight:500;font-size:26px;">通用后台管理系统</div>
<div class="layui-form-item">
<label class="layui-form-label">用户名</label>
<div class="layui-input-block">
<input type="text" class="layui-input" name="username">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">密码</label>
<div class="layui-input-block">
<input type="password" class="layui-input" name="pwd">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">验证码</label>
<div class="layui-input-inline">
<input type="text" class="layui-input" name="vericode">
</div>
<img id="captcha" src="/admins/account/captcha" style="width: 168px;height:36px;border: 1px solid;color:#cdcdcd; cursor:pointer;" onclick="reload_captcha()">
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" onclick="dologin()">登录</button>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
layui.use(['layer'],function(){
$ = layui.jquery;
layer = layui.layer;
});
//登录
function dologin(){
var username = $.trim($('input[name="username"]').val());
var pwd = $.trim($('input[name="pwd"]').val())
var vericode = $.trim($('input[name="vericode"]').val());
var _token = $('input[name="_token"]').val();
if(username==''){
return layer.alert('请输入用户名',{icon:2});
}
if(pwd==''){
return layer.alert('请输入密码',{icon:2});
}
if(vericode==''){
return layer.alert('请输入验证码',{icon:2});
}
$.post('/admins/account/dologin',{_token:_token,username:username,pwd:pwd,vericode:vericode},
function(res){
if(res.code>0){
return layer.alert(res.msg,{icon:2});
}
layer.msg(res.msg);
setTimeout(function(){window.location.href='/admins/home/index';},1000);
},'json');
}
function reload_captcha(){
$('#captcha').attr('src','/admins/account/captcha?rand='+Math.random());
}
</script>
(2)Account.php
<?php
namespace App\Http\Controllers\admins;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
//后台账号
class Account extends Controller
{
//后台登录
public function login(){
return view('/admins/account/login');
}
public function dologin(Request $request){
$username = $request->username;
$pwd = $request->pwd;
$VeriCode = $request->vericode;
session_start();
$sess_code = $_SESSION['code'];
if($VeriCode!=$sess_code){
exit(json_encode(array('code'=>1,'msg'=>'验证码错误')));
}
//查询数据库,校验用户名和密码
if($username==''){
exit(json_encode(array('code'=>1,'msg'=>'用户名不能为空')));
}
if($pwd==''){
exit(json_encode(array('code'=>1,'msg'=>'密码不能为空')));
}
$res = Auth::attempt(['username'=>$username,'password'=>$pwd]);
if(!$res){
exit(json_encode(array('code'=>1,'msg'=>'帐号或密码错误')));
}
return json_encode(array('code'=>0,'msg'=>'登录成功'));
}
//验证码
public function captcha(){
VeriCode::create();
}
}
/**
* 验证码类
*/
class VeriCode{
// 获取验证码配置
private static function _getCodeConfig(){
return [
// 验证码字符集
'codeStr' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
// 验证码个数
'codeCount' => 4,
// 字体大小
'fontsize' =>16,
// 验证码的宽度
'width' => 100,
// 验证码高度
'height' => 36,
// 是否有干扰点?true有,false没有
'disturbPoint' => true,
// 干扰点个数,disturbPoint开启后生效
'pointCount' => 200,
// 是否有干扰条?true有,false没有
'disturbLine' => true,
// 干扰条个数,disturbLine开启后生效
'lineCount' => 3
];
}
// 创建图片验证码
public static function create(){
// 配置
$config = self::_getCodeConfig();
//创建画布
$image = imagecreatetruecolor($config['width'],$config['height']);
//背景颜色
$bgcolor=imagecolorallocate($image,255,255,255);
imagefill($image,0,0,$bgcolor);
$captch_code = '';//存储验证码
$captchCodeArr = str_split($config['codeStr']);
//随机选取4个候选字符
for($i=0;$i<$config['codeCount'];$i++){
$fontsize = $config['fontsize'];
$fontcolor=imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));//随机颜色
$fontcontent = $captchCodeArr[rand(0,strlen($config['codeStr'])-1)];
$captch_code.=$fontcontent;
$_x = $config['width']/$config['codeCount'];
$x=($i*(int)$_x)+rand(5,10); //随机坐标
$y=rand(5,10);
imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor); // 水平地画一行字符串
}
session_start();
$_SESSION['code']=$captch_code;
//增加干扰点
if($config['disturbPoint']){
for($i=0;$i<$config['pointCount'];$i++){
$pointcolor=imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));
imagesetpixel($image,rand(1,99),rand(1,29),$pointcolor);
}
}
//增加干扰线
if($config['disturbLine']){
for($i=0;$i<$config['lineCount'];$i++){
$linecolor=imagecolorallocate($image,rand(80,280),rand(80,220),rand(80,220));
imageline($image,rand(1,99),rand(1,29),rand(1,99),rand(1,29),$linecolor);
}
}
//输出格式
header('content-type:image/png');
imagepng($image);
//销毁图片
imagedestroy($image);
}
}
(3)home.php
<?php
namespace App\Http\Controllers\admins;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
//后台主页
class Home extends Controller
{
public function index(){
$data['menus'] = DB::table('admin_menu')->where('pid',0)->where('ishidden',0)
->where('status',0)->get()->toArray();
//echo '<pre>';
// print_r($data['menus']);
foreach($data['menus'] as $key => $val){
$childs = DB::table('admin_menu')->where('pid',$val->mid)
->where('ishidden',0)->where('status',0)->get()->all();
$data['menus'][$key]->child = $childs;
}
return view('/admins/home/index',$data);
}
//后台首页欢迎页面
public function welcome(){
return view('admins/home/welcome');
}
}
(3)index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="/static/plugins/layui/css/layui.css">
<script type="text/javascript" src="/static/plugins/layui/layui.js"></script>
<title>欢迎使用</title>
<style>
.top-header{height: 50px;background-color: #01AAED;line-height: 50px;color: #fff;padding: 0px 10px;}
.top-header .top-title{font-size: 20px;}
.top-header .top-account{float:right}
.top-header a{color: blue;}
.left-menu{position: absolute;width: 200px;background-color:#333744 ;}
.left-menu .layui-colla-title{background-color: #393D49;color: #fff;font-size: 14px;}
.left-menu .layui-colla-content{border-color:#393D49;padding: 0px;}
.left-menu .layui-colla-item{border-color:#393D49 ;}
.left-menu .layui-nav-tree{width: 198px;}
.left-menu .layui-collapse{border: none;}
.main{position:absolute;left:200px;right: 0px;}
.main iframe{width:100%;height:100%;}
</style>
</head>
<body>
<!--header-->
<div class="top-header">
<span class="top-title">后台管理系统</span>
<div class="top-account">
<span style="font-size:20px;" class="layui-icon layui-icon-friends"></span>
<span style="color:red" class="top-username">admin</span>
<a href="javascript:;" onclick="logout()">退出</a>
</div>
</div>
<!--left menu左侧菜单-->
<div class="left-menu">
<div class="layui-collapse">
@foreach($menus as $menu)
<div class="layui-colla-item">
<h2 class="layui-colla-title">{{$menu->title}}</h2>
<div class="layui-colla-content ">
<ul class="layui-nav layui-nav-tree" id="L_demoNav" lay-filter="test">
@foreach($menu->child as $chd)
<li class="layui-nav-item">
<a href="javascript:;" onclick="firemenu(this)" controller="{{$chd->controller}}"
action="{{$chd->action}}">{{$chd->title}}</a>
</li>
@endforeach
</ul>
</div>
</div>
@endforeach
<!-- <div class="layui-colla-item">
<h2 class="layui-colla-title">权限管理</h2>
<div class="layui-colla-content ">内容区域</div>
</div>
<div class="layui-colla-item">
<h2 class="layui-colla-title">系统设置</h2>
<div class="layui-colla-content ">内容区域</div>
</div> -->
</div>
</div>
<!--main 主操作区-->
<div class="main">
<iframe frameborder="0" src="/admins/home/welcome" onload="resetIframeHeight(this)"></iframe>
</div>
</body>
</html>
<script type="text/javascript">
layui.use('element', function(){
var element = layui.element;
$ = layui.jquery;
//设置菜单高度
var left_height = document.documentElement.clientHeight - 50;
console.log(left_height);
$('.left-menu').height(left_height);
});
function resetIframeHeight(obj){
var leftHeight = parent.document.documentElement.clientHeight - 50;
$('.main').height(leftHeight);
}
function firemenu(obj){
var controller = $(obj).attr('controller');
var action = $(obj).attr('action');
var url = '/admins/'+controller+'/'+action;
$('.main iframe').attr('src',url);
}
</script>
(4)welcome.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>欢迎使用</title>
</head>
<body>
<div style="text-align: center;font-size:18px;margin-top:100px;color:blue"><h2>欢迎使用后台管理系统</h2></div>
</body>
</html>
(5)DBServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Query\Builder as QueryBuilder;
class DBServiceProvider extends ServiceProvider
{
public function boot(){
//返回数组列表
QueryBuilder::macro('lists',function(){
$data = $this->get()->toArray();
$result = [];
foreach($data as $val){
$result[] = (array)$val;
}
return $result;
});
}
}
(6)admin.php
<?php
namespace App\Http\Controllers\admins;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
//管理员管理
class admin extends Controller{
//账号列表
public function index(){
$data['admins'] = DB::table('admin')->lists();
foreach ($data['admins'] as $key => $val) {
$group = DB::table('admin_group')->where('gid',$val['gid'])->first();
$data['admins'][$key]['group_title'] = $group->title;
}
return view('admins.admin.index',$data);
}
}
(7)app.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL', null),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'en',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
Illuminate\Bus\BusServiceProvider::class,
Illuminate\Cache\CacheServiceProvider::class,
Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
Illuminate\Cookie\CookieServiceProvider::class,
Illuminate\Database\DatabaseServiceProvider::class,
Illuminate\Encryption\EncryptionServiceProvider::class,
Illuminate\Filesystem\FilesystemServiceProvider::class,
Illuminate\Foundation\Providers\FoundationServiceProvider::class,
Illuminate\Hashing\HashServiceProvider::class,
Illuminate\Mail\MailServiceProvider::class,
Illuminate\Notifications\NotificationServiceProvider::class,
Illuminate\Pagination\PaginationServiceProvider::class,
Illuminate\Pipeline\PipelineServiceProvider::class,
Illuminate\Queue\QueueServiceProvider::class,
Illuminate\Redis\RedisServiceProvider::class,
Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
Illuminate\Session\SessionServiceProvider::class,
Illuminate\Translation\TranslationServiceProvider::class,
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
//扩展DBServiceProvider
App\Providers\DBServiceProvider::class,
],
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'App' => Illuminate\Support\Facades\App::class,
'Arr' => Illuminate\Support\Arr::class,
'Artisan' => Illuminate\Support\Facades\Artisan::class,
'Auth' => Illuminate\Support\Facades\Auth::class,
'Blade' => Illuminate\Support\Facades\Blade::class,
'Broadcast' => Illuminate\Support\Facades\Broadcast::class,
'Bus' => Illuminate\Support\Facades\Bus::class,
'Cache' => Illuminate\Support\Facades\Cache::class,
'Config' => Illuminate\Support\Facades\Config::class,
'Cookie' => Illuminate\Support\Facades\Cookie::class,
'Crypt' => Illuminate\Support\Facades\Crypt::class,
'DB' => Illuminate\Support\Facades\DB::class,
'Eloquent' => Illuminate\Database\Eloquent\Model::class,
'Event' => Illuminate\Support\Facades\Event::class,
'File' => Illuminate\Support\Facades\File::class,
'Gate' => Illuminate\Support\Facades\Gate::class,
'Hash' => Illuminate\Support\Facades\Hash::class,
'Http' => Illuminate\Support\Facades\Http::class,
'Lang' => Illuminate\Support\Facades\Lang::class,
'Log' => Illuminate\Support\Facades\Log::class,
'Mail' => Illuminate\Support\Facades\Mail::class,
'Notification' => Illuminate\Support\Facades\Notification::class,
'Password' => Illuminate\Support\Facades\Password::class,
'Queue' => Illuminate\Support\Facades\Queue::class,
'Redirect' => Illuminate\Support\Facades\Redirect::class,
'Redis' => Illuminate\Support\Facades\Redis::class,
'Request' => Illuminate\Support\Facades\Request::class,
'Response' => Illuminate\Support\Facades\Response::class,
'Route' => Illuminate\Support\Facades\Route::class,
'Schema' => Illuminate\Support\Facades\Schema::class,
'Session' => Illuminate\Support\Facades\Session::class,
'Storage' => Illuminate\Support\Facades\Storage::class,
'Str' => Illuminate\Support\Str::class,
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
],
];
二.相关演练效果图:
1.登录后台跳转到欢迎页面:
2.管理员列表页面:
3.管理员列表信息页面:
4.中间件限制非登录访问页面:
三.学习总结:
这节课学习的对象转换数组还不是很熟,因为前面的基础没有学好,没有时间进行练习,照老师的录播课顺利通过,其中有出现小问题,自己把代码敲错了,现在学习进度还没有跟上节奏,需勤加练习,现在感觉越来越有趣,待跟上进度过后再从头反复练习,将基础打牢。