What is the best practice for adding constants in laravel? (Long List)

后端 未结 11 739
猫巷女王i
猫巷女王i 2021-01-30 06:21

I am rather new to laravel. I have a basic question, What is the best way to add constants in laravel. I know the .env method that we use to add the constants. Also I have mad

相关标签:
11条回答
  • 2021-01-30 06:59

    In addition to Arun Singh's answer I would recommend you to use helpers.

    Inside your helper.php you may define

    if ( ! function_exists('constants'))
    {
        function constants($key)
        {
           return config('constants.' . $key);
        }
    }
    

    Thus instead of

    Config::get('constants.options');
    Config::get('constants.options.option_attachment');
    

    you may call

    constants('options');
    constants('options.option_attachment');
    
    0 讨论(0)
  • 2021-01-30 07:02

    I use aliased class constants :

    First, create your class that contain your constants : App/MyApp.php for exemple

    namespace App;
    
    class MyApp {
       const MYCONST = 'val';
    }
    

    Then add it to the aliased classes in the config/app.php

    'aliases' => [
      //...
      'MyApp' => App\MyApp::class,
    

    Finally use them wherever you like (controllers or even blades) :

    MyApp::MYCONST
    
    0 讨论(0)
  • 2021-01-30 07:08

    For most constants used globally across the application, storing them in config files is sufficient. It is also pretty simple

    Create a new file in the config directory. Let's call it constants.php

    In there you have to return an array of config values.

    return [
        'options' => [
            'option_attachment' => '13',
            'option_email' => '14',
            'option_monetery' => '15',
            'option_ratings' => '16',
            'option_textarea' => '17',
        ]
    ];
    

    And you can access them as follows

    Config::get('constants.options');
    // or if you want a specific one
    Config::get('constants.options.option_attachment');
    
    0 讨论(0)
  • 2021-01-30 07:11

    First you make Constants folder inside your app directory.

    And then you make Constants.php. Define your constants in this file

    For Example :

    define('ONE', '1');
    define('TWO', '2');
    

    And you modify the composer.json

    Alternatively, you can use composer.json to load the bootstrap/constants.php file by adding the following code to the “autoload” section, like so:

    "autoload": {
        "files": [
            "bootstrap/constants.php"
        ]
    }
    

    And update your composer !

    0 讨论(0)
  • 2021-01-30 07:13

    You can create a file named paths.php in root directory/config/paths.php

    Insert this data into paths.php

    define('OPTION_ATTACHMENT', 13);
    define('OPTION_EMAIL', 14);
    define('OPTION_MONETERY', 15);
    define('OPTION_RATINGS', 16);
    define('OPTION_TEXTAREA', 17);
    

    Note : make sure to run command : php artisan config:clear

    0 讨论(0)
提交回复
热议问题