Global Access of variable in Laravel Views
To make the variable accessible globally, such as in a header across your application, you can use the View::share method in your AppServiceProvider.
Step 1: open App\Providers\AppServiceProvider and use boot() method as below
public function boot()
{
Paginator::useBootstrap();
// Share the `today_count` variable globally across all views
\Illuminate\Support\Facades\View::composer('*', function ($view) { \\or use \Illuminate\Support\Facades and then View::component(*)
$todo_list = \App\Models\Todo::query();
$today_count = $todo_list->count();
$view->with('today_count', $today_count); // Share the `today_count` with all views
});
}
Step 2: Access variable in Your Views
<div>
Today's Todo Count: {{ $today_count }}
</div>
Important Notes:
The View::composer('*', ...) method shares the variable across all views. If you only want it in specific views, you can replace '*' with specific view names.
View::composer(['header', 'dashboard', 'partials.sidebar']