一,文档地址:
https://docs.golaravel.com/docs/middleware
注意选择11这个版本
二,添加全局中间件时,需要添加到bootstrap/app.php文件中:
1,
use App\Http\Middleware\EnsureTokenIsValid;
->withMiddleware(function (Middleware $middleware) {
$middleware->append(EnsureTokenIsValid::class);
})
说明:append方法同时支持数组和字串,即此处可以是一个数组,传递多个中间件
2, 整体形式如下:
require __DIR__ . '/global_functions.php';
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
//
$middleware->append(ApiSign::class);
})
->withExceptions(function (Exceptions $exceptions) {
$exceptions->respond(function (Response $response, Throwable $exception) {
$env = env('APP_ENV');
//本地和测试 环境时,打印文件和行数,生产环境只打印信息
if ($env == 'local' || $env == 'testing') {
$msg = $exception->getMessage().' '.$exception->getFile().' '.$exception->getLine();
} else {
$msg = $exception->getMessage();
}
return Result::ErrorCode($exception->getCode(),$msg);
});
})->create();
三,全局中间件例子:
1,使用中间件
->withMiddleware(function (Middleware $middleware) {
$middleware->prepend(SomeMiddleware::class);
$middleware->append(AnotherMiddleware::class);
$middleware->remove(UnwantedMiddleware::class);
$middleware->replace(OldMiddleware::class, NewMiddleware::class);
})
2,可以定义并修改一个中间件组
->withMiddleware(function (Middleware $middleware) {
$middleware->group('custom', [
FirstMiddleware::class,
SecondMiddleware::class,
]);
$middleware->prependToGroup('web', NewWebMiddleware::class);
$middleware->appendToGroup('api', NewApiMiddleware::class);
$middleware->removeFromGroup('web', OldWebMiddleware::class);
$middleware->replaceInGroup('api', OldApiMiddleware::class, NewApiMiddleware::class);
})
3,手动管理laravel的全局中间件
->withMiddleware(function (Middleware $middleware) {
$middleware->use([
// \Illuminate\Http\Middleware\TrustHosts::class,
\Illuminate\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Http\Middleware\ValidatePostSize::class,
\Illuminate\Foundation\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
]);
})
标签:__,Http,Middleware,中间件,middleware,laravel11,全局,class From: https://www.cnblogs.com/architectforest/p/18456281