1. 什么是laravel
Laravel是一套简洁、优雅的PHP Web开发框架(PHP Web Framework)。它可以让你从面条一样杂乱的代码中解脱出来;它可以帮你构建一个完美的网络APP,而且每行代码都可以简洁、富于表达力。
在Laravel中已经具有了一套高级的PHP ActiveRecord实现 — Eloquent ORM。它能方便的将“约束(constraints)”应用到关系的双方,这样你就具有了对数据的完全控制,而且享受到ActiveRecord的所有便利。Eloquent原生支持Fluent中查询构造器(query-builder)的所有方法。
2. 数据库配置
根目录.env文件设置
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=数据库名
DB_USERNAME=数据库用户 一般是root
DB_PASSWORD=数据库密码 一般是root
3. 时区设置
config目录下的app.php
搜索
'timezone' => 'UTC',
改为
'timezone' => 'PRC',
4. 项目开发内容
4.1 账号登陆验证
<?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 Account extends Controller
{
//后台登录
public function login() {
return view('admins/account/login');
}
public function dologin(Request $request) {
$username=$request->username;
$pwd=$request->pwd;
// echo '<pre>';
// print_r($pwd);
// die();
$vericode=$request->vericode;
session_start();
$session_code=$_SESSION['code'];
if (strtolower($vericode)!=strtolower($session_code)) {
exit(json_encode(['code'=>1,'message'=>'验证码错误']));
}
//查询数据库,校验用户名和密码的正确性
// $res=DB::table('admin')->where('name',"$username")->where('password',"$pwd")->get()->all();
// if (empty($res)) {
// exit(json_encode(['code'=>1,'message'=>'账号或者密码错误']));
// }
// session_start();
// setcookie('adminName',$username);
// setcookie('passWord',$pwd);
$res=Auth::attempt(['name' => $username, 'password' => $pwd]);
if (!$res) {
exit(json_encode(['code'=>1,'message'=>'账号密码错误']));
}
$data['time']=date('Y-m-d H:i:s');
$data['ip']=$request->getClientIp();
DB::table('admin')->where('name',$username)->update($data);
return json_encode(['code'=>0,'message'=>'登录成功']);
}
//退出登录
public function logout() {
Auth::logout();
return json_encode(['code'=>0,'message'=>'退出后台成功,请保管好账号密码']);
}
//验证码
public function VeriCode() {
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);
}
}
4.2 权限菜单设置
<?php
namespace App\Http\Controllers\admins;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
//菜单管理
class Menus extends Controller
{
// 菜单列表
public function index(Request $request) {
$mid=(int)$request->mid;//int null的值是一个0
$data['lists']=DB::table('admin_menu')->where('pid',$mid)->lists();//列出主菜单和下级菜单
$data['premenu']=DB::table('admin_menu')->where('mid',$mid)->item();
// echo '<pre>';
// print_r($data);
return view('admins/menus/index',$data);
}
// 添加菜单
public function add(Request $request)
{
$pid=$request->pid;
$data['pid']=$pid;
return view('admins/menus/add',$data);
}
// 保存菜单
public function save(Request $request)
{
$mid=(int)$request->mid;
$data['pid']=(int)$request->pid;
$data['title']=trim($request->title);
$data['ord']=(int)$request->ord;
$data['controller']=trim($request->controller);
$data['action']=trim($request->action);
$data['ishidden']=(int)$request->ishidden;
$data['status']=(int)$request->status;
if ($data['title']==''){
exit(json_encode(['code'=>1,'message'=>'菜单名称不能为空']));
}
if ($mid===0) {
DB::table('admin_menu')->insert($data);
} else {
DB::table('admin_menu')->where('mid',$mid)->update($data);
}
exit(json_encode(['code'=>0,'message'=>'菜单添加成功']));
}
//编辑菜单
public function edit(Request $request)
{
$mid=(int)$request->mid;
$data['menu']=DB::table('admin_menu')->where('mid',$mid)->item();
return view('admins/menus/edit',$data);
}
// 删除菜单
public function del(Request $request)
{
$mid=(int)$request->mid;
DB::table('admin_menu')->where('mid',$mid)->delete();
exit(json_encode(['code'=>0,'message'=>'删除菜单成功']));
}
}
4.3 管理员用户权限设置
<?php
namespace App\Http\Controllers\admins;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use function GuzzleHttp\json_decode;
// 角色管理
class Groups extends Controller
{
//角色列表
public function index(Request $request) {
$data['lists']=DB::table('admin_group')->select('gid','title')->lists();
return view('admins/groups/index',$data);
}
// 角色添加
public function add(Request $request) {
$gid=(int)$request->gid;
// var_dump($gid);
$data['current_group']=DB::table('admin_group')->where('gid',$gid)->item();
if(!$data['current_group']){
$data['current_group']['gid']=0;
$data['current_group']['title']='';
$data['current_group']['rights']=[];
}
if($data['current_group'] && $data['current_group']['rights']) {
$data['current_group']['rights'] = json_decode($data['current_group']['rights']);
}
// $data['current_group']['rights']=[];
// if($data['current_group']['rights']) {
// }
// echo '<pre>';
// print_r($data);
// return;
//查询所有菜单权限,除禁用外的
$data['menus']=DB::table('admin_menu')->where('pid',0)->where('status',0)->lists();
$all_menu=DB::table('admin_menu')->where('status',0)->lists();
foreach ($data['menus'] as $key => $value) {
foreach ($all_menu as $v) {
if($value['mid']===$v['pid']){
$data['menus'][$key]['children'][]=$v;
}
}
}
// echo '<pre>';
// print_r($data['menus']);
// return;
return view('admins/groups/add',$data);
}
public function save(Request $request) {
$gid=(int)$request->gid;
$data['title']=trim($request->title);
$menus=$request->menus;
$menus=array_keys($menus);
$data['rights']=json_encode($menus);
// echo '<pre>';
// print_r($data);
if($gid===0) {
DB::table('admin_group')->insert($data);
} else {
DB::table('admin_group')->where('gid',$gid)->update($data);
}
// return view('admins/groups/save',$data);
exit(json_encode(['code'=>0,'message'=>'角色添加成功']));
}
//删除角色账号
public function del(Request $request) {
$gid=(int)$request->gid;
// echo $aid;
// exit;
DB::table('admin_group')->where('gid',$gid)->delete();
exit(json_encode(['code'=>0,'message'=>'删除成功']));
}
}
4.4 网站设置
<?php
namespace App\Http\Controllers\admins;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use function GuzzleHttp\json_decode;
class Setting extends Controller
{
//基础设置首页
public function index()
{
$data['item']= DB::table('setting')->where('name','site_setting')->item();
if($data['item']) {
$data['item']['vals']=json_decode($data['item']['vals'],true);
}
// echo '<pre>';
// print_r($data['item']['vals']);
# code...
return view('admins/setting/index',$data);
}
//保存设置
public function save(Request $request)
{
$data['title']=$request->title;
$data['keywords']=$request->keywords;
$data['email']=$request->email;
$data['beian']=$request->beian;
$data['desc']=$request->desc;
$data['closeweb']=$request->closeweb;
if($data['title']===''){
exit(json_encode(['code'=>1,'message'=>'站点名称不能为空']));
}
$item= DB::table('setting')->where('name','site_setting')->item();
if($item) {
DB::table('setting')->where('name','site_setting')->update(['name'=>'site_setting','vals'=>json_encode($data)]);
}else {
DB::table('setting')->insert(['name'=>'site_setting','vals'=>json_encode($data)]);
}
exit(json_encode(['code'=>0,'message'=>'保存成功']));
}
}
4.5 不同权限菜单显示/隐藏
<?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;
use function GuzzleHttp\json_decode;
//后台主页
class Home extends Controller
{
//后台登录
public function index() {
$admin=Auth::user();
$gid=$admin->gid;
$myrights=DB::table('admin_group')->where('gid',$gid)->item();
// echo '<pre>';
// print_r($myrights);
// return;
$myrights=json_decode($myrights['rights'],true);
$data['menus']=DB::table('admin_menu')->whereIn('mid',$myrights)->where('pid',0)->where('ishidden',0)->where('status',0)->get()->all();
foreach($data['menus'] as $key=>$val) {
$childs=DB::table('admin_menu')->whereIn('mid',$myrights)->where('pid',$val->mid)->where('ishidden',0)->where('status',0)->get()->all();
$data['menus'][$key]->child=$childs;
}
// echo '<pre>';
// print_r($data);
$data['admin']=$admin;
return view('admins/home/index',$data);
}
//后台首页欢迎页面
public function welcome() {
return view('admins/home/welcome');
}
}
4.6 路由Route
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('admins\Account\login');
});
//后台登录
Route::get('/admins/account/login','admins\Account@login')->name('login');
Route::post('/admins/account/dologin','admins\Account@dologin');
Route::get('/admins/account/logout','admins\Account@logout');
// 后台验证码
Route::get('/admins/account/VeriCode','admins\Account@VeriCode');
//路由分组
Route::namespace('admins')->middleware(['auth','rights'])->group(function(){
//后台首页
Route::get('/admins/home/index','Home@index');
Route::get('/admins/home/welcome','Home@welcome');
//管理员账号管理
Route::get('/admins/admin/index','Admin@index');//列表
Route::get('/admins/admin/add','Admin@add');//添加账号
Route::post('/admins/admin/save','Admin@save');//保存账号
Route::post('/admins/admin/del','Admin@del');//删除账号
Route::get('/admins/admin/edit','Admin@edit');//编辑账号
//菜单管理
Route::get('/admins/menus/index','Menus@index');//菜单列表
Route::get('/admins/menus/add','Menus@add');//添加菜单
Route::post('/admins/menus/save','Menus@save');//保存菜单
Route::get('/admins/menus/edit','Menus@edit');//保存菜单
Route::post('/admins/menus/del','Menus@del');//删除菜单
//角色相关
Route::get('/admins/groups/index','Groups@index');//菜单列表
Route::get('/admins/groups/add','Groups@add');//添加菜单
Route::post('/admins/groups/save','Groups@save');//保存权限
Route::post('/admins/groups/del','Groups@del');//删除角色权限
// 站点设置
Route::get('/admins/setting/index','Setting@index');
Route::post('/admins/setting/save','Setting@save');//保存
});
4.7 中间件权限验证
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use function GuzzleHttp\json_decode;
class Rightvalidate
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
private function norights($request,$message) {
if ($request->ajax()){
return response(json_encode(['code'=>1,'message'=>$message]),200);
}
return response($message,200);
}
// 权限验证中间件
public function handle($request, Closure $next)
{
$admin=Auth::user();
$gid=$admin->gid; //当前用户的gid角色
$group=DB::table('admin_group')->where('gid',$gid)->item();
if (!$group) {
return $this->norights($request,'该角色不存在');
}
// echo '<pre>';
// print_r($group);
// 所拥有的权限
$rights=[];
if($group['rights']) {
$rights=json_decode($group['rights'],true);
}
// 当前用户访问的是哪个菜单
$res=$request->route()->action['controller'];
// 字符串切割成关联数组
$res=explode('\\',$res);
$res=$res[count($res)-1];
$res=explode('@',$res);
// 查询当前url对应的菜单id
$current_menu=DB::table('admin_menu')->where('controller',$res[0])->where('action',$res[1])->item();
//判断该mid是否在rights数组中
if(!$current_menu) {
return $this->norights($request,'功能不存在');
}
if($current_menu['status']===1) {
return $this->norights($request,'状态禁用');
}
if (!in_array($current_menu['mid'],$rights)) {
return $this->norights($request,'权限不足哦');
}
// echo '<pre>';
// print_r($current_menu);
return $next($request);
}
}
4.8 查询数据统一数组输出
4.9 演示地址
http://www.php520.vip/
测试账号:admin 密码:123456 权限:超管
测试账号:ceshi 密码:123456 权限:普管
5. 总结
Laravel 在快速建立方面非常优秀,而且因为使用的人越来越多,现在也有非常丰富的第三方库,而且 Laravel 框架一直都在使用 PHP 最新的一些技术,这也是我喜欢这个框架的一个原因。在线上环境,如果数据库需要一些初始数据,可以使用 migration 完成,不使用 Seed 主要有两个原因,一、Seed 会依赖一些 开发环境的包 ,例如 faker 等,而这些包是在 require-dev 中,二, 使用 Seed 可能会和开发环境的 Seed 混淆。