Reputation: 143
In laravel, there is no constant file defined, so I went on and searched for a way to implement the use of constants. The method below is what I managed to put together:
// app/config/constants.php
return['CONSTANT_NAME' => 'value'];
// index.blade.php
{{ Config::get('constants.CONSTANT_NAME') }}
Now, my question is; is there a cleaner way of retrieving my constants in my view? Something like:
{{ Constant::get('CONSTANT_NAME') }}
This is in order to keep my view nice, short and clean.
Appreciate the input!
Upvotes: 11
Views: 23471
Reputation: 391
In v5 you can do like @msturdy suggests except you store the constant in the .env file or in production as actual $_ENVIRONMENT variables on your server for your environment.
Example .env entry:
CONSTANT=value
Then call like so:
View::share('bladeConstant', env('CONSTANT'));
Then load it with:
{{ bladeConstant }}
Upvotes: 2
Reputation: 10794
One thing you can do is to share pieces of data across your views:
View::share('my_constant', Config::get('constants.CONSTANT_NAME'));
Put that at the top of your routes.php
and the constant will then be accessible in all your blade views as:
{{ $my_constant }}
Upvotes: 9
Reputation: 180024
The Config
class is intended to replace the need for constants and serves the same role.
Have app/config/constants.php
return an array of key/value pairs, then just use Config::get('constants.key')
to access them.
You could conceivably create a Constant
class that has a get
function as a shortcut:
class Constant {
public function get($key) {
return Config::get('constants.' . $key);
}
}
but using the standard Laravel handling is likely to be nicer to other Laravel developers trying to familiarize themselves with your code.
Upvotes: 4