I need to be able to pass data to all views when the user is logged in.
Here is what my AppServiceProvider
currently looks like:
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
if (Auth::check())
{
View::share('key', 'value');
}
}
}
However, the data is never passed to the view because I can't use Auth
(for some reason) in AppServiceProvider
so the if statement condition is never met.
Following a previous solution I found, I tried doing this:
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
View::composer('*', function ($view)
{
if (Auth::check())
{
View::share('key', 'value');
}
}
}
}
This worked, but the problem is that the closure is called whenever a view is rendered.
For example, if my blade template includes 3 other blade templates (which it does), then the closure above will be called 4 times. Explained further here.
So how can I access the user correctly in AppServiceProvider
?