Laravel 5将数据从中间件传递到控制器 [英] Laravel 5 Pass Data from Middleware to Controller

查看:247
本文介绍了Laravel 5将数据从中间件传递到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的中间件类似于Auth.它检查URL模式(例如:/rest/*),然后在请求中查找令牌,并从数据库中检索其相应的用户.之后,我想将该用户保存在变量中,以便以后可以在以下任何控制器中使用它.最好的方法是什么?

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?

中间件:

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);
}

在控制器中:

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

推荐答案

我会将数据刷新到会话中.当您刷新数据时,它只会停留在该位置,直到下一个请求.

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

在您的中间件中添加

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');

这里是文档链接以供参考 http://laravel.com/docs/5.0/session#flash-data

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

这篇关于Laravel 5将数据从中间件传递到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆