Blogger Information
Blog 30
fans 1
comment 0
visits 24015
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
路由中间件20191108
阿乎乎的学习
Original
894 people have browsed it

第一步 创建中间件。创建中间件的方法,手动创建在\app\Http\Middleware创建一个名为CheckUser.php的文件,添加命名空间app\Http\Middleware,使用Closure类。或者artisan命令行创建 php artisan make:middleware CheckUser。还是命令行创建简单一点,不用自己写命名空间和使用类。

实例

<?php
namespace app\Http\Middleware;
use Closure;
class CheckUser{
    public function handle($req,Closure $next){
         //设定一个简单角色名称的验证
         $user=$_GET['user'];
         //如果user不等于admin返回无权查看,如果等于则继续执行控制器中的方法
         if($user!='admin'){
             echo '你没有权限查看';
               }
         return $next($req);
         }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

第二步 注册中间件。在app\Http\下的Kernel.php中的protected $routeMiddleware中添加自己需要执行的中间件。'check' => \App\Http\Middleware\CheckUser::class,

第三步 创建新的控制器CheckUser.php

实例

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class CheckUser extends Controller
{
    public function check(){
        echo 'hello middware';
    }
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

第四步 设置路由 

实例

<?php
Route::get('check','CheckUser@check')->middleware('check');

运行实例 »

点击 "运行实例" 按钮查看在线实例

进行访问

111.png

222.png




Correction status:qualified

Teacher's comments:中间件, 类似控制器的前置操作, 可起到请求过滤器的作用
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!