任何方法都可以改变Auth::user()
返回的用户实例,我想要的是急于加载一些与它的关系,所以我不必每次都输入它:
从Auth::user();
来Auth::user()->with('company')->first();
和每次我请求Auth::user()
我得到Auth::user()->with('company')->first()
返回。
一种方法是编辑before
滤镜(app/filters.php
)。
App::before(function($request)
{
if (Auth::check())
{
Auth::setUser(Auth::user()->with('company')->first());
}
});
这样你仍然可以在任何你需要的地方使用Auth::user()
我遵循的一个方法是在BaseController中设置Auth::user(),它将在所有控制器中访问。如果你在视图中使用,你可以View::share()使它在所有视图中可用。在这里你可以加载你的关系。
class BaseController extends Controller {
protected $currentUser;
public function __construct() {
$this->currentUser = Auth::user(); // You can eager load here. This is will null if not logged in
}
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
View::share('currentUser', $this->currentUser);
}