在中间件内获取到一个变量,如何返回到控制器中并使用这个变量!

回复内容:

在中间件内获取到一个变量,如何返回到控制器中并使用这个变量!

做了个demo:

// web.php
Route::get('/check', 'CheckController@check')->middleware(App\Http\Middleware\CheckRequest::class);

// Middleware/CheckRequest.php
class CheckRequest
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $check_request = 'CheckRequest';
        $request->attributes->add(compact('check_request'));
        return $next($request);
    }
}

// CheckController.php
//use Request;
use Illuminate\Http\Request;
class CheckController extends Controller
{
    public function check(Request $request)
    {
        return $request->get('check_request'); // 输出CheckRequest
    }
    
    public function check2()
    {
        return Request::get('check_request'); // 输出CheckRequest
    }
}
登录后复制
09-13 17:08