laravel自定义中间件实例
laravel自定义中间件实例
一、总结
一句话总结:
二、laravel自定义中间件实例
1、中间件位置和代码
legend3/app/Http/Middleware/Home/UploadLessonMiddleware.php
<?php namespace App\Http\Middleware\Home; use App\Models\BaHome\AaUser\AbUserSetting\Get\GetUserSetting; use Closure; use Auth; //上传功能中间件 class UploadLessonMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { //前端的上传功能中间件 //用来判断用户是否有上传课程、上传视频、上传博客的权限 //如果登录成功就进行下一步 //如果没有登录成功就返回到登录页 if(!Auth::guard('user')->check()){ return redirect('/login'); }else{ //如果登录了 $u_id=Auth::guard('user')->user()->id; $u_id=intval($u_id); $user_setting=GetUserSetting::byUID($u_id); //有发布课程的权限 if($user_setting['us_can_publish_lesson']){ //进行下一步操作 return $next($request); }else{ return redirect('/no_upload_lesson_permission'); } } } }
2、注册中间件
legend3/app/Http/Kernel.php
protected $routeMiddleware = [ //fry //后端的登录中间件注册 'admin.auth'=>Middleware\Admin\Admin::class, //前端的登录中间件注册 'home.auth'=>Middleware\Home\User::class, //发布课程权限中间件 'upload_lesson'=>Middleware\Home\UploadLessonMiddleware::class, 省略若干无关代码........... ]
3、使用中间件
class CreateLessonController extends CommonController { public function __construct() { //排除'index'方法,进行中间件的验证 $this->middleware('upload_lesson')->except(['no_upload_lesson_permission']); } 省略若干无关代码........... }
可以写个方法来显示没通过权限验证的消息
//没有上传课程权限的中间件返回显示信息 public function no_upload_lesson_permission(){ $validate_message='你没有权限发布课程、章节、视频!!'; $error_data=['validate_message']; return view('home.ya_common.validate_return_page.validate_return_page',compact($error_data)); }