How to change the value of Auth::user() in Laravel 4

别等时光非礼了梦想. 提交于 2019-12-11 17:52:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!