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