问题
Any way to change the user instance returned by Auth::user()
, what I want is to eager load some relations with it, so i don't have to keep typing it every time:
from
Auth::user();
to
Auth::user()->with('company')->first();
and every time I request the Auth::user()
I get the Auth::user()->with('company')->first()
returned.
回答1:
One way of doing it is to edit your before
filter (app/filters.php
).
App::before(function($request)
{
if (Auth::check())
{
Auth::setUser(Auth::user()->with('company')->first());
}
});
That way you can still use Auth::user()
wherever you need.
回答2:
One method which I follow is to set the Auth::user() in the BaseController and it will beaccessible in all the controllers. If you are using in Views you can View::share() to make it available in all views. Here you can eager load your relationships.
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);
}
来源:https://stackoverflow.com/questions/25040787/how-to-change-the-value-of-authuser-in-laravel-4