The best way would be sharing the variable using View::share('var', $value);
Problems with composing using "*"
:
Consider following approach:
<?php
// from AppServiceProvider::boot()
$viewFactory = $this->app->make(Factory::class);
$viewFacrory->compose('*', GlobalComposer::class);
From an example blade view:
@for($i = 0; $i<1000; $i++)
@include('some_partial_view_to_display_i', ['toDisplay' => $i])
@endfor
What happens?
GlobalComposer
class is instantiated 1000 times using
App::make
. composing:some_partial_view_to_display_i
is handled
1000 times.compose
function inside the GlobalComposer
class is called 1000 times.But the partial view some_partial_view_to_display_i
has nothing to do with the variables composed by GlobalComposer
but heavily increases render time.
Best approach?
Using View::share
along a grouped middleware.
Route::group(['middleware' => 'WebMiddleware'], function(){
// Web routes
});
Route::group(['prefix' => 'api'], function (){
});
class WebMiddleware {
public function handle($request)
{
\View::share('user', auth()->user());
}
}
Update
If you are using something that is computed over the middleware pipeline you can simply listen to the proper event or put the view share middleware at the last bottom of the pipeline.