Laravel 5 Pass Data from Middleware to Controller

2019-04-06 05:12发布

My middleware is similar to Auth. It checks for a URL pattern (eg: /rest/*), and then looks for token in the request, retrieves its corresponding user from database. After that, I want to save that user in a variable so that I can get back to it later in any of the following controller. What's the best way?

Middleware:

public function handle($request, Closure $next)
{
    $token = Input::get("token");
    // get user data from database
    $user = User::get_user_from_token($token);
    // ?? -> How to pass $user to controller, so that ..
    return $next($request);
}

In Controller:

public function profile_save() {
    // I get the user back here without querying again
    $user = ???
}

标签: laravel-5
2条回答
倾城 Initia
2楼-- · 2019-04-06 05:41

I would flash the data to the session. When you flash data it only stays there until the next request.

In your middleware add

Session::flash('user', $user);

Don't forget to add this at the top of your middle ware

use Session;

Then whenever you need to access your user use

Session::get('user');

Here is a link to the docs for reference http://laravel.com/docs/5.0/session#flash-data

查看更多
来,给爷笑一个
3楼-- · 2019-04-06 05:45

I'm using Laravel 5.1. To pass parameters from the middleware to the controller you can add it to the Request object.

In the middleware:

public function handle($request, Closure $next)
{
    $user = 'DB Call To Get User';
    $age = 20;
    $request->route()->setParameter('user', $user);
    $request->route()->setParameter('age', $age);
    return $next($request);
}

Then you can get the user in the controller from either the arguments:

public function TestAction(Request $request, User $user, $age)
{}

Or explicitly from the request object:

public function TestAction(Request $request)
{
    $user = $request->route()->getParameter('user');
    $age = $request->route()->getParameter('age');
}

Of course you can flash the data temporarily to the session or save it to the session itself and set an expiry time, but if you only need it to last for the lifetime of the request then i think this is a good way.

Hope this helps!

查看更多
登录 后发表回答