{"flag":true,"single":true,"pageTitle":"Global Access of variable in Laravel Views","post":{"id":252,"user_id":"1","slug":"global-access-of-variable-in-laravel-views-imri","title":"Global Access of variable in Laravel Views","body":"<p>To make the variable accessible globally, such as in a header across your application, you can use the <strong>View::share<\/strong> method in your AppServiceProvider.&nbsp;<\/p>\r\n<p><strong>Step 1:&nbsp;<\/strong> open <strong>App\\Providers\\AppServiceProvider and use boot() method as below<\/strong><\/p>\r\n<pre class=\"language-markup\"><code>public function boot()\r\n    {\r\n        Paginator::useBootstrap();\r\n        \/\/ Share the `today_count` variable globally across all views\r\n        \\Illuminate\\Support\\Facades\\View::composer('*', function ($view) {   \\\\or use \\Illuminate\\Support\\Facades and then View::component(*)\r\n            $todo_list = \\App\\Models\\Todo::query();\r\n            $today_count = $todo_list-&gt;count();\r\n            $view-&gt;with('today_count', $today_count);             \/\/ Share the `today_count` with all views\r\n        });\r\n    }<\/code><\/pre>\r\n<p><strong>Step 2:<\/strong>&nbsp;Access variable in Your Views<\/p>\r\n<pre class=\"language-markup\"><code>&lt;div&gt;\r\n    Today's Todo Count: {{ $today_count }}\r\n&lt;\/div&gt;<\/code><\/pre>\r\n<p><strong>Important Notes:<\/strong><br>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.<\/p>\r\n<pre class=\"language-markup\"><code>View::composer(['header', 'dashboard', 'partials.sidebar']<\/code><\/pre>","category_id":"2","is_private":"0","created_at":"2024-08-13T13:37:14.000000Z","updated_at":"2024-08-13T13:37:14.000000Z","category":{"id":2,"user_id":"1","name":"Laravel Core","slug":"laravel-nhyt","parent_id":"1","created_at":"2023-03-14T03:58:27.000000Z","updated_at":"2023-03-20T11:30:50.000000Z"},"user":{"id":1,"name":"R GONDAL","email":"rizikmw@gmail.com","email_verified_at":null,"two_factor_confirmed_at":null,"current_team_id":"1","profile_photo_path":null,"created_at":"2023-03-12T10:49:33.000000Z","updated_at":"2025-01-10T12:59:00.000000Z","profile_photo_url":"https:\/\/ui-avatars.com\/api\/?name=R+G&color=7F9CF5&background=EBF4FF"}},"pageDesc":"To make the variable accessible globally, such as in a header across your application, you can use the View::share method in your AppService - Global Access of variable in Laravel Views (Updated: August 13, 2024) - Read more about Global Access of variable in Laravel Views at my programming site [SITE]","categories":[]}