Laravel share Auth::User() info

2019-07-29 01:52发布

I made a BaseController to share user information but that doesn't work. Auth::user()->id and Auth::user()->email are empty.

How can I archive this? Whats the best approach?

class BaseAdminController extends Controller{
    public function __construct()
    {
        $this->initMenu();
    }

    private function initMenu()
    {
       View::share('userinfo', (object) ['id' => Auth::User()->id, 'email' => Auth::User()->email]);
    }
}

标签: laravel-5
2条回答
相关推荐>>
2楼-- · 2019-07-29 01:57

You can do it via middleware because you can't access the session or authenticated user in the controller's constructor, since the middlware isn't runnig yet:

class BaseAdminController extends Controller{
    public function __construct()
    {
        $this->middleware(function ($request, $next) {

            $this->initMenu();

            return $next($request);
        });
    }

    private function initMenu()
    {
       View::share('userinfo', (object) ['id' => Auth::User()->id, 'email' => Auth::User()->email]);
    }
}
查看更多
Bombasti
3楼-- · 2019-07-29 02:12

You can use the view helper function to share stuff easily. Maybe this will help you:

view()->share('userinfo', [...data to pass in an array...]);

or

view()->share('user', Auth::user());

This is an example! Only pas the info you want to the view, like you did in your example. But just pass the array, not casting it to object, etc....

查看更多
登录 后发表回答