Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Pass Data from Middleware to Controller

Tags:

laravel-5

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 = ???
}
like image 691
Sanjay Vamja Avatar asked May 21 '15 12:05

Sanjay Vamja


2 Answers

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

like image 171
Chris Townsend Avatar answered Oct 28 '22 11:10

Chris Townsend


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!

like image 20
omarjebari Avatar answered Oct 28 '22 12:10

omarjebari