php - Variable is undefined Make the variable optional in the blade template after using view composer

I've been trying to define a variable globally into my project (laravel 7). I need this variable be available in all views but i am getting following error:

$count is undefined
Make the variable optional in the blade template. Replace {{ $count }} with {{ $count ?? '' }}

First step i created a new service provider TestSeriviceProvider

Second step I added following line to congif\app.php

 App\Providers\TestServiceProvider::class,

Then i wrote following codes into boot method of TestServiceProvider

 public function boot()
    {

        View::composer('*', function ($view) {

            $view->with('count', 333);
        });
    }

Which part have i made mistake?

Answer

Solution:

This can be done in the boot() method of the AppServiceProvider.

Just add view()->share('count', 333); and your $count is accessible on any blade page. If you have many shared data implemented, yes you can make a separate ServiceProvider for this. But keep in mind that your shared data may be overwritten in controllers.

Depending on the reason why you want to do this, you can look into a combination of middleware and the session() helper or combine shared variables in an array.

Source