Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by whitelisting our website.

How to define Global Variable or Constant in Laravel

We often need to define global variables/constants for our application, like Status, Conditions, Countries (we can put all countries in table as it will be along array/object), also weekdays, weekends and e.t.c. vary on projects.

Status (Active, Inactive) and Conditions (Ok, Good, Better, Best) or Grade (F, C, D, A, A-, A+), so like these type of variables/constants,  we write same code multiple times. But if we set all of these as Global Variables then we can use these anytime, anywhere in application.

 

 

And here I am presenting how to define GLOBAL Variable/Constant in Laravel 5.2. (This is not the only way, but I like it)

  1. First create a file named constants.php on config directory
  2. And code some variables like below

return [

‘STATUS’ => [

1 => ‘Active’,

0 => ‘Inactive’

],

‘Conditions’ => [

1 => ‘Ok’,

2 => ‘Good,

3 => ‘Better,

4 => ‘Best’

 

],

‘GRADE’ => [

‘A+’ => ‘A+’,

‘A’ => ‘A’,

‘A-’ => ‘A-’,

‘B’ => ‘B’,

‘C’ => ‘C’,

‘D’ => ‘D’,

‘F’ => ‘F’

]

];

  1. Now, how can we use/access this Global Variables? Very easy, and we can also access these variables on view too.

Config::get(‘constants. STATUS’); // it will output status array.

Or, if we want a specific one element then

Config::get(‘constants. GRADE.F’); // output: F

  1. And lastly we can also set Global variable only for the current request. This will not persist.

Config::set(‘constants. Conditions.5’, ‘Not Stable’)

 

And finally – if you like this article please inspire me by posting a comment (at below) for the next article 😉 . And I don’t mind if you want to share among with your friends, bocz. Sharing’s Caring.

 

Credit: google, stackoverflow, Laravel.io, Laravel docs and etc.

One thought on “How to define Global Variable or Constant in Laravel

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Wordpress Social Share Plugin powered by Ultimatelysocial