Home >Backend Development >PHP Tutorial >How to pass variables generated by laravel in middleware to the controller

How to pass variables generated by laravel in middleware to the controller

WBOY
WBOYOriginal
2016-09-30 09:37:281150browse

Get a variable in the middleware, how to return to the controller and use this variable!

Reply content:

Get a variable in the middleware, how to return to the controller and use this variable!

Made a demo:

<code>// 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
    }
}
</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn