Using global constants and arrays in Laravel 5

Most of the time developers need to create common and global set of constants, variables and arrays which could be used anywhere in your application. There is a handy way to do it in Laravel 5.

In fact you can create it as a part of configuration settings in Laravel 5. All you need to do is define your common set of variables in a file and save it under the config directory. You can include this file anywhere in your application by using simple call to configuration methods.

Here is an example where an array is saved in the file and then called and used in a controller.

Array is saved in plain php code in config/myvars.php file.

return [
     "categories" => [
         "Logo & identity",
         "Web & app design",
         "Business & advertising"
         ……
     ],
     'usstates' => [
         "Alabama",
         "Alaska",
         "Arizona",
         ……..
     ]
 ];

To use it in Laravel App here is how it is called. For example I use it in my PagesController. At the top of controller and under the namesspaces declaration I call the Config class as under

namespace App\Http\Controllers;
use Config;

And inside the method of the conroller I read the categories and states array:

$categories = Config::get('myvars.categories');
$usstates = Config::get('myvars.usstates');

Leave a Reply