博客列表 >laravel通用后台管理系统项目开发

laravel通用后台管理系统项目开发

我是郭富城
我是郭富城原创
2020年06月16日 06:21:521627浏览

1. 什么是laravel

Laravel是一套简洁、优雅的PHP Web开发框架(PHP Web Framework)。它可以让你从面条一样杂乱的代码中解脱出来;它可以帮你构建一个完美的网络APP,而且每行代码都可以简洁、富于表达力。
在Laravel中已经具有了一套高级的PHP ActiveRecord实现 — Eloquent ORM。它能方便的将“约束(constraints)”应用到关系的双方,这样你就具有了对数据的完全控制,而且享受到ActiveRecord的所有便利。Eloquent原生支持Fluent中查询构造器(query-builder)的所有方法。

2. 数据库配置

根目录.env文件设置

  1. DB_CONNECTION=mysql
  2. DB_HOST=127.0.0.1
  3. DB_PORT=3306
  4. DB_DATABASE=数据库名
  5. DB_USERNAME=数据库用户 一般是root
  6. DB_PASSWORD=数据库密码 一般是root

3. 时区设置

config目录下的app.php

  1. 搜索
  2. 'timezone' => 'UTC',
  3. 改为
  4. 'timezone' => 'PRC',

4. 项目开发内容

4.1 账号登陆验证

  1. <?php
  2. namespace App\Http\Controllers\admins;
  3. use App\Http\Controllers\Controller;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\Auth;
  6. use Illuminate\Support\Facades\DB;
  7. //后台账号
  8. class Account extends Controller
  9. {
  10. //后台登录
  11. public function login() {
  12. return view('admins/account/login');
  13. }
  14. public function dologin(Request $request) {
  15. $username=$request->username;
  16. $pwd=$request->pwd;
  17. // echo '<pre>';
  18. // print_r($pwd);
  19. // die();
  20. $vericode=$request->vericode;
  21. session_start();
  22. $session_code=$_SESSION['code'];
  23. if (strtolower($vericode)!=strtolower($session_code)) {
  24. exit(json_encode(['code'=>1,'message'=>'验证码错误']));
  25. }
  26. //查询数据库,校验用户名和密码的正确性
  27. // $res=DB::table('admin')->where('name',"$username")->where('password',"$pwd")->get()->all();
  28. // if (empty($res)) {
  29. // exit(json_encode(['code'=>1,'message'=>'账号或者密码错误']));
  30. // }
  31. // session_start();
  32. // setcookie('adminName',$username);
  33. // setcookie('passWord',$pwd);
  34. $res=Auth::attempt(['name' => $username, 'password' => $pwd]);
  35. if (!$res) {
  36. exit(json_encode(['code'=>1,'message'=>'账号密码错误']));
  37. }
  38. $data['time']=date('Y-m-d H:i:s');
  39. $data['ip']=$request->getClientIp();
  40. DB::table('admin')->where('name',$username)->update($data);
  41. return json_encode(['code'=>0,'message'=>'登录成功']);
  42. }
  43. //退出登录
  44. public function logout() {
  45. Auth::logout();
  46. return json_encode(['code'=>0,'message'=>'退出后台成功,请保管好账号密码']);
  47. }
  48. //验证码
  49. public function VeriCode() {
  50. VeriCode::create();
  51. }
  52. }
  53. /**
  54. * 验证码类
  55. */
  56. class VeriCode{
  57. // 获取验证码配置
  58. private static function _getCodeConfig(){
  59. return [
  60. // 验证码字符集
  61. 'codeStr' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
  62. // 验证码个数
  63. 'codeCount' => 4,
  64. // 字体大小
  65. 'fontsize' =>16,
  66. // 验证码的宽度
  67. 'width' => 100,
  68. // 验证码高度
  69. 'height' => 36,
  70. // 是否有干扰点?true有,false没有
  71. 'disturbPoint' => true,
  72. // 干扰点个数,disturbPoint开启后生效
  73. 'pointCount' => 200,
  74. // 是否有干扰条?true有,false没有
  75. 'disturbLine' => true,
  76. // 干扰条个数,disturbLine开启后生效
  77. 'lineCount' => 3
  78. ];
  79. }
  80. // 创建图片验证码
  81. public static function create(){
  82. // 配置
  83. $config = self::_getCodeConfig();
  84. //创建画布
  85. $image = imagecreatetruecolor($config['width'],$config['height']);
  86. //背景颜色
  87. $bgcolor=imagecolorallocate($image,255,255,255);
  88. imagefill($image,0,0,$bgcolor);
  89. $captch_code = '';//存储验证码
  90. $captchCodeArr = str_split($config['codeStr']);
  91. //随机选取4个候选字符
  92. for($i=0;$i<$config['codeCount'];$i++){
  93. $fontsize = $config['fontsize'];
  94. $fontcolor=imagecolorallocate($image,rand(0,120),rand(0,120),rand(0,120));//随机颜色
  95. $fontcontent = $captchCodeArr[rand(0,strlen($config['codeStr'])-1)];
  96. $captch_code.=$fontcontent;
  97. $_x = $config['width']/$config['codeCount'];
  98. $x=($i*(int)$_x)+rand(5,10); //随机坐标
  99. $y=rand(5,10);
  100. imagestring($image,$fontsize,$x,$y,$fontcontent,$fontcolor); // 水平地画一行字符串
  101. }
  102. session_start();
  103. $_SESSION['code']=$captch_code;
  104. //增加干扰点
  105. if($config['disturbPoint']){
  106. for($i=0;$i<$config['pointCount'];$i++){
  107. $pointcolor=imagecolorallocate($image,rand(50,200),rand(50,200),rand(50,200));
  108. imagesetpixel($image,rand(1,99),rand(1,29),$pointcolor);
  109. }
  110. }
  111. //增加干扰线
  112. if($config['disturbLine']){
  113. for($i=0;$i<$config['lineCount'];$i++){
  114. $linecolor=imagecolorallocate($image,rand(80,280),rand(80,220),rand(80,220));
  115. imageline($image,rand(1,99),rand(1,29),rand(1,99),rand(1,29),$linecolor);
  116. }
  117. }
  118. //输出格式
  119. header('content-type:image/png');
  120. imagepng($image);
  121. //销毁图片
  122. imagedestroy($image);
  123. }
  124. }

4.2 权限菜单设置

  1. <?php
  2. namespace App\Http\Controllers\admins;
  3. use App\Http\Controllers\Controller;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\DB;
  6. //菜单管理
  7. class Menus extends Controller
  8. {
  9. // 菜单列表
  10. public function index(Request $request) {
  11. $mid=(int)$request->mid;//int null的值是一个0
  12. $data['lists']=DB::table('admin_menu')->where('pid',$mid)->lists();//列出主菜单和下级菜单
  13. $data['premenu']=DB::table('admin_menu')->where('mid',$mid)->item();
  14. // echo '<pre>';
  15. // print_r($data);
  16. return view('admins/menus/index',$data);
  17. }
  18. // 添加菜单
  19. public function add(Request $request)
  20. {
  21. $pid=$request->pid;
  22. $data['pid']=$pid;
  23. return view('admins/menus/add',$data);
  24. }
  25. // 保存菜单
  26. public function save(Request $request)
  27. {
  28. $mid=(int)$request->mid;
  29. $data['pid']=(int)$request->pid;
  30. $data['title']=trim($request->title);
  31. $data['ord']=(int)$request->ord;
  32. $data['controller']=trim($request->controller);
  33. $data['action']=trim($request->action);
  34. $data['ishidden']=(int)$request->ishidden;
  35. $data['status']=(int)$request->status;
  36. if ($data['title']==''){
  37. exit(json_encode(['code'=>1,'message'=>'菜单名称不能为空']));
  38. }
  39. if ($mid===0) {
  40. DB::table('admin_menu')->insert($data);
  41. } else {
  42. DB::table('admin_menu')->where('mid',$mid)->update($data);
  43. }
  44. exit(json_encode(['code'=>0,'message'=>'菜单添加成功']));
  45. }
  46. //编辑菜单
  47. public function edit(Request $request)
  48. {
  49. $mid=(int)$request->mid;
  50. $data['menu']=DB::table('admin_menu')->where('mid',$mid)->item();
  51. return view('admins/menus/edit',$data);
  52. }
  53. // 删除菜单
  54. public function del(Request $request)
  55. {
  56. $mid=(int)$request->mid;
  57. DB::table('admin_menu')->where('mid',$mid)->delete();
  58. exit(json_encode(['code'=>0,'message'=>'删除菜单成功']));
  59. }
  60. }

4.3 管理员用户权限设置

  1. <?php
  2. namespace App\Http\Controllers\admins;
  3. use App\Http\Controllers\Controller;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\DB;
  6. use function GuzzleHttp\json_decode;
  7. // 角色管理
  8. class Groups extends Controller
  9. {
  10. //角色列表
  11. public function index(Request $request) {
  12. $data['lists']=DB::table('admin_group')->select('gid','title')->lists();
  13. return view('admins/groups/index',$data);
  14. }
  15. // 角色添加
  16. public function add(Request $request) {
  17. $gid=(int)$request->gid;
  18. // var_dump($gid);
  19. $data['current_group']=DB::table('admin_group')->where('gid',$gid)->item();
  20. if(!$data['current_group']){
  21. $data['current_group']['gid']=0;
  22. $data['current_group']['title']='';
  23. $data['current_group']['rights']=[];
  24. }
  25. if($data['current_group'] && $data['current_group']['rights']) {
  26. $data['current_group']['rights'] = json_decode($data['current_group']['rights']);
  27. }
  28. // $data['current_group']['rights']=[];
  29. // if($data['current_group']['rights']) {
  30. // }
  31. // echo '<pre>';
  32. // print_r($data);
  33. // return;
  34. //查询所有菜单权限,除禁用外的
  35. $data['menus']=DB::table('admin_menu')->where('pid',0)->where('status',0)->lists();
  36. $all_menu=DB::table('admin_menu')->where('status',0)->lists();
  37. foreach ($data['menus'] as $key => $value) {
  38. foreach ($all_menu as $v) {
  39. if($value['mid']===$v['pid']){
  40. $data['menus'][$key]['children'][]=$v;
  41. }
  42. }
  43. }
  44. // echo '<pre>';
  45. // print_r($data['menus']);
  46. // return;
  47. return view('admins/groups/add',$data);
  48. }
  49. public function save(Request $request) {
  50. $gid=(int)$request->gid;
  51. $data['title']=trim($request->title);
  52. $menus=$request->menus;
  53. $menus=array_keys($menus);
  54. $data['rights']=json_encode($menus);
  55. // echo '<pre>';
  56. // print_r($data);
  57. if($gid===0) {
  58. DB::table('admin_group')->insert($data);
  59. } else {
  60. DB::table('admin_group')->where('gid',$gid)->update($data);
  61. }
  62. // return view('admins/groups/save',$data);
  63. exit(json_encode(['code'=>0,'message'=>'角色添加成功']));
  64. }
  65. //删除角色账号
  66. public function del(Request $request) {
  67. $gid=(int)$request->gid;
  68. // echo $aid;
  69. // exit;
  70. DB::table('admin_group')->where('gid',$gid)->delete();
  71. exit(json_encode(['code'=>0,'message'=>'删除成功']));
  72. }
  73. }

4.4 网站设置

  1. <?php
  2. namespace App\Http\Controllers\admins;
  3. use App\Http\Controllers\Controller;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\DB;
  6. use function GuzzleHttp\json_decode;
  7. class Setting extends Controller
  8. {
  9. //基础设置首页
  10. public function index()
  11. {
  12. $data['item']= DB::table('setting')->where('name','site_setting')->item();
  13. if($data['item']) {
  14. $data['item']['vals']=json_decode($data['item']['vals'],true);
  15. }
  16. // echo '<pre>';
  17. // print_r($data['item']['vals']);
  18. # code...
  19. return view('admins/setting/index',$data);
  20. }
  21. //保存设置
  22. public function save(Request $request)
  23. {
  24. $data['title']=$request->title;
  25. $data['keywords']=$request->keywords;
  26. $data['email']=$request->email;
  27. $data['beian']=$request->beian;
  28. $data['desc']=$request->desc;
  29. $data['closeweb']=$request->closeweb;
  30. if($data['title']===''){
  31. exit(json_encode(['code'=>1,'message'=>'站点名称不能为空']));
  32. }
  33. $item= DB::table('setting')->where('name','site_setting')->item();
  34. if($item) {
  35. DB::table('setting')->where('name','site_setting')->update(['name'=>'site_setting','vals'=>json_encode($data)]);
  36. }else {
  37. DB::table('setting')->insert(['name'=>'site_setting','vals'=>json_encode($data)]);
  38. }
  39. exit(json_encode(['code'=>0,'message'=>'保存成功']));
  40. }
  41. }

4.5 不同权限菜单显示/隐藏

  1. <?php
  2. namespace App\Http\Controllers\admins;
  3. use App\Http\Controllers\Controller;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\Auth;
  6. use Illuminate\Support\Facades\DB;
  7. use function GuzzleHttp\json_decode;
  8. //后台主页
  9. class Home extends Controller
  10. {
  11. //后台登录
  12. public function index() {
  13. $admin=Auth::user();
  14. $gid=$admin->gid;
  15. $myrights=DB::table('admin_group')->where('gid',$gid)->item();
  16. // echo '<pre>';
  17. // print_r($myrights);
  18. // return;
  19. $myrights=json_decode($myrights['rights'],true);
  20. $data['menus']=DB::table('admin_menu')->whereIn('mid',$myrights)->where('pid',0)->where('ishidden',0)->where('status',0)->get()->all();
  21. foreach($data['menus'] as $key=>$val) {
  22. $childs=DB::table('admin_menu')->whereIn('mid',$myrights)->where('pid',$val->mid)->where('ishidden',0)->where('status',0)->get()->all();
  23. $data['menus'][$key]->child=$childs;
  24. }
  25. // echo '<pre>';
  26. // print_r($data);
  27. $data['admin']=$admin;
  28. return view('admins/home/index',$data);
  29. }
  30. //后台首页欢迎页面
  31. public function welcome() {
  32. return view('admins/home/welcome');
  33. }
  34. }

4.6 路由Route

  1. <?php
  2. use Illuminate\Support\Facades\Route;
  3. /*
  4. |--------------------------------------------------------------------------
  5. | Web Routes
  6. |--------------------------------------------------------------------------
  7. |
  8. | Here is where you can register web routes for your application. These
  9. | routes are loaded by the RouteServiceProvider within a group which
  10. | contains the "web" middleware group. Now create something great!
  11. |
  12. */
  13. Route::get('/', function () {
  14. return view('admins\Account\login');
  15. });
  16. //后台登录
  17. Route::get('/admins/account/login','admins\Account@login')->name('login');
  18. Route::post('/admins/account/dologin','admins\Account@dologin');
  19. Route::get('/admins/account/logout','admins\Account@logout');
  20. // 后台验证码
  21. Route::get('/admins/account/VeriCode','admins\Account@VeriCode');
  22. //路由分组
  23. Route::namespace('admins')->middleware(['auth','rights'])->group(function(){
  24. //后台首页
  25. Route::get('/admins/home/index','Home@index');
  26. Route::get('/admins/home/welcome','Home@welcome');
  27. //管理员账号管理
  28. Route::get('/admins/admin/index','Admin@index');//列表
  29. Route::get('/admins/admin/add','Admin@add');//添加账号
  30. Route::post('/admins/admin/save','Admin@save');//保存账号
  31. Route::post('/admins/admin/del','Admin@del');//删除账号
  32. Route::get('/admins/admin/edit','Admin@edit');//编辑账号
  33. //菜单管理
  34. Route::get('/admins/menus/index','Menus@index');//菜单列表
  35. Route::get('/admins/menus/add','Menus@add');//添加菜单
  36. Route::post('/admins/menus/save','Menus@save');//保存菜单
  37. Route::get('/admins/menus/edit','Menus@edit');//保存菜单
  38. Route::post('/admins/menus/del','Menus@del');//删除菜单
  39. //角色相关
  40. Route::get('/admins/groups/index','Groups@index');//菜单列表
  41. Route::get('/admins/groups/add','Groups@add');//添加菜单
  42. Route::post('/admins/groups/save','Groups@save');//保存权限
  43. Route::post('/admins/groups/del','Groups@del');//删除角色权限
  44. // 站点设置
  45. Route::get('/admins/setting/index','Setting@index');
  46. Route::post('/admins/setting/save','Setting@save');//保存
  47. });

4.7 中间件权限验证

  1. <?php
  2. namespace App\Http\Middleware;
  3. use Closure;
  4. use Illuminate\Support\Facades\Auth;
  5. use Illuminate\Support\Facades\DB;
  6. use function GuzzleHttp\json_decode;
  7. class Rightvalidate
  8. {
  9. /**
  10. * Handle an incoming request.
  11. *
  12. * @param \Illuminate\Http\Request $request
  13. * @param \Closure $next
  14. * @return mixed
  15. */
  16. private function norights($request,$message) {
  17. if ($request->ajax()){
  18. return response(json_encode(['code'=>1,'message'=>$message]),200);
  19. }
  20. return response($message,200);
  21. }
  22. // 权限验证中间件
  23. public function handle($request, Closure $next)
  24. {
  25. $admin=Auth::user();
  26. $gid=$admin->gid; //当前用户的gid角色
  27. $group=DB::table('admin_group')->where('gid',$gid)->item();
  28. if (!$group) {
  29. return $this->norights($request,'该角色不存在');
  30. }
  31. // echo '<pre>';
  32. // print_r($group);
  33. // 所拥有的权限
  34. $rights=[];
  35. if($group['rights']) {
  36. $rights=json_decode($group['rights'],true);
  37. }
  38. // 当前用户访问的是哪个菜单
  39. $res=$request->route()->action['controller'];
  40. // 字符串切割成关联数组
  41. $res=explode('\\',$res);
  42. $res=$res[count($res)-1];
  43. $res=explode('@',$res);
  44. // 查询当前url对应的菜单id
  45. $current_menu=DB::table('admin_menu')->where('controller',$res[0])->where('action',$res[1])->item();
  46. //判断该mid是否在rights数组中
  47. if(!$current_menu) {
  48. return $this->norights($request,'功能不存在');
  49. }
  50. if($current_menu['status']===1) {
  51. return $this->norights($request,'状态禁用');
  52. }
  53. if (!in_array($current_menu['mid'],$rights)) {
  54. return $this->norights($request,'权限不足哦');
  55. }
  56. // echo '<pre>';
  57. // print_r($current_menu);
  58. return $next($request);
  59. }
  60. }

4.8 查询数据统一数组输出

4.9 演示地址

http://www.php520.vip/
测试账号:admin 密码:123456 权限:超管
测试账号:ceshi 密码:123456 权限:普管

5. 总结

Laravel 在快速建立方面非常优秀,而且因为使用的人越来越多,现在也有非常丰富的第三方库,而且 Laravel 框架一直都在使用 PHP 最新的一些技术,这也是我喜欢这个框架的一个原因。在线上环境,如果数据库需要一些初始数据,可以使用 migration 完成,不使用 Seed 主要有两个原因,一、Seed 会依赖一些 开发环境的包 ,例如 faker 等,而这些包是在 require-dev 中,二, 使用 Seed 可能会和开发环境的 Seed 混淆。

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议
P粉5015095942022-12-11 17:11:591楼
你好,我点开演示地址的时候显示不存在,请问一下有什么方法可以查看演示吗?