I think your question can ultimately be reduced to the following:
Where can I set the long-term value available globally in my application?
The obvious answer is that it depends. Several factors depend on this:
- Will the value ever be different or will it be the same for everyone?
- How long does it last? (Forever? One day? One viewing session?)?
Config
If the value is the same for everyone and rarely changes, the best place will probably be indicated in the configuration file somewhere under app/config , for example. app/config/companyname.php :
<?php return [ 'somevalue' => 10, ];
You can access this value from anywhere in the application through Config::get('companyname.somevalue')
Session
If the value that you are going to store will be different for each user, the most logical place to place it is Session . This is what you are talking about in your question, but using the wrong syntax. The correct syntax for storing a variable in a session is:
Session::put('somekey', 'somevalue');
The correct syntax for returning it later is:
Session::get('somekey');
How much when you perform these operations is a little up to you. I would choose a route filter if on Laravel 4.x or Middleware , if you use Laravel 5. The following is an example of using a route filter that uses a different class to actually come up with a value:
// File: ValueMaker.php (saved in some folder that can be autoloaded) class ValueMaker { public function makeValue() { return 42; } } // File: app/filters.php is probably the best place Route::filter('set_value', function() { $valueMaker = app()->make('ValueMaker'); Session::put('somevalue', $valueMaker->makeValue()); }); // File: app/routes.php Route::group(['before' => 'set_value'], function() { // Value has already been 'made' by this point. return View::make('view') ->with('value', Session::get('somevalue')) ; });
Jeff lambert
source share