laware的"Afterware"

Cod*_*der 2 php laravel

我现在正在使用中间件,我现在关注的是:

中间件可以在控制器之前运行,但是在控制器向用户发出响应之前是否可以运行中间件?

我想在执行控制器后设置一些标题.

谢谢

Ham*_*bot 5

实际上,可以使用中间件来修改请求和响应.

以下是中间件评论的基本结构:

<?php

namespace App\Http\Middleware;

use Closure;

class SomeMiddleware
{
    public function handle($request, Closure $next)
    {

        // Here, you can perform action before passing it to the controllers

        $response = $next($request);

        // Here, you get back the response generated by the controllers 
        // and you can add cookies or anything you want

        return $response;
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,使用$response = $next($request);就像是在将请求传递给控制器​​之前和之后要做的事情的分隔符.

资料来源:https://laravel.com/docs/5.3/middleware#defining-middleware