Blogger Information
Blog 34
fans 0
comment 0
visits 22903
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
第7章 laravel 框架基础6-2019年11月08日20时00分
Tommy-黄天浩的博客
Original
645 people have browsed it

作业:创建一个路由中间件,并通过访问url地址来触发中间件输出一名话:‘hello middware’

先新建一个中间件,这里采用命令行创建,执行如下代码:

php artisan make:middleware Check

运行后如下图所示:

QQ截图20191121012821.png

Check.php代码如下所示:

<?php

namespace App\Http\Middleware;

use Closure;

class Check
{
    //注意这里必需是handle
    public function handle($req,Closure $next){
        $username='admin';
        if($username != 'admin'){
            exit('没有权限操作');
        }

        echo 'Hello Middleware!';
        return $next($req);
    }
}

紧接着注册中间件(必需的步骤),在kernel.php这个文件添加代码:

QQ截图20191121012926.png

找到这一块的代码,新增最后一行,注册中间件:

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    //在这里添加后面的代码
    'check' => \App\Http\Middleware\Check::class
];

新建控制器文件Home.php:

<?php

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

class Home extends Controller
{
    public function index(Request $req){
        
    }
}

最后添加路由的代码,在web.php文件里面:

Route::get('/Home','Home@index')->middleware('check');
//这里的check就是在注册路由的时候的Key值

运行后效果如下图所示:

QQ截图20191121014628.png

注意使用中间件的时候一定要注册,还有中间件方法名称必需为handle

Correcting teacher:天蓬老师天蓬老师

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