Share Values to all Controller & Views in Laravel


Sharing is caring!

Laravel is one of the best modern php framework as it have all updated features. Most of the Laravel Developers may crossed this situation that they need some values throughout the application without re-intilized. Here is the ultimate solution to do the task effectively.

What Method we using

We using Application Service Provider to do this trick which is more effective and useful feature in laravel.

Service providers are the central place of all application bootstrapping. Your own application, as well as all of Laravel’s core services are bootstrapped via service providers. You can find more details about AppServiceProvider in Official Documentation

Step#1: Define values in Laravel AppServiceProvider

You should create default values in AppServiceProvider before using it on your controller and views.

Go to App/Providers Folder.
Open AppServiceProvider.php.

Step#2: Define Values

In AppServiceProvider you can see Boot function. Here we declare the default values for overall application bootstrapped.
Here we initilize 100 as default value throughout the application

For Views

For Controller

Full Coding

Step#3: Retrive the Data

This is coding for how to retrive the data from views & controller.

From Views with Blade Template

From Controller

Hope you learned this useful trick and it reduces your repeated initilization in laravel as well. Like to know more methods to share values throughout the application. Please comment if you have any ideas, suggestions.

Sharing is caring!

Related posts:

About KARTHIK 119 Articles
IT Consultant, Photographer, Blogger