There so many things in website which is common in every page and you need to define them as global variable to share with every pages.
For example, Every website has their title, logo and some of footer information which is shared in every pages.
In Laravel, you can easily define them in AppServiceProvider either using composer() method or share() method.
Here, I will show you how to define global variable and how to use them in your blade file.
This is very helpful to define some common variable as global because you can use them from anywhere in your blade file.
You need to open your AppServiceProvider.php
file and put following line of code to share variable in view file.
- <?php
- namespace App\Providers;
- use Illuminate\Support\ServiceProvider;
- class AppServiceProvider extends ServiceProvider
- {
- /**
- * Bootstrap any application services.
- *
- * @return void
- */
- public function boot()
- {
- view()->share('pageTitle', 'Expertphp.in');
- }
- /**
- * Register any application services.
- *
- * @return void
- */
- public function register()
- {
- //
- }
- }
You can use composer()
method to define global variable same as you define using share()
method.
- <?php
- namespace App\Providers;
- use Illuminate\Support\ServiceProvider;
- class AppServiceProvider extends ServiceProvider
- {
- /**
- * Bootstrap any application services.
- *
- * @return void
- */
- public function boot()
- {
- view()->composer('*', function ($view) {
- $view->with('pageTitle', 'Expertphp.in');
- });
- }
- /**
- * Register any application services.
- *
- * @return void
- */
- public function register()
- {
- //
- }
- }
Now you can use "pageTitle" variable in your every blade file :
{{ $pageTitle }}