简单的测试代码
需要在控制器中运行中间件,但它不起作用 另外,如果使用随机密钥更改中间件密钥,则忽略它并回显仅回显“构造”字符串
<?php namespace App\Http\Controllers; use Closure; use Illuminate\Http\Request; class RootController extends Controller { public function __construct() { $this->middleware('middleware.key'); echo 'construct<br>'; } public function test(){ return 'test'; } }
<?php namespace App\Http\Middleware; use App\Http\Controllers\Controller; use Closure; use Illuminate\Http\Request; class TestMiddleware extends Controller { public function handle(Request $request, Closure $next) { echo 'middleware'; return $next($request); } }
output is : construct test
您必须从
app/Http/Kernel.php
注册中间件并将中间件添加到您的路由中。https://laravel.com/docs/9 .x/middleware#将中间件分配给路由