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
View::share("default_value",'100');
For Controller
$this->app->singleton('default_value', function () { return 100; });
Full Coding
class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. */ public function boot() { View::share("default_value",'100'); $this->app->singleton('default_value', function () { return 100; }); } }
Step#3: Retrive the Data
This is coding for how to retrive the data from views & controller.
From Views with Blade Template
{{ $default_value }}
From Controller
public function data(){ return app('default_value'); }
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.