skip to Main Content

I googled "laravel constants". All articles say, create "config/myfile.php".

<?php
return [
    ...
];

I thought "constant" means define()

define('DIR_IMAGE', '/var/www/html/storage/app/public/image')

I really want to use define()。 ChatGPT suggests /bootstrap/app.php

At the end, I add

define('HTTP_CATALOG', env('APP_URL'));
define('DIR_STORAGE', base_path() . '/storage/app/public/');

echo HTTP_CATALOG; exit;

The "HTTP_CATALOG" is empty. $_ENV[‘APP_URL’] is empty, too.

echo print_r($_ENV, true); exit;

Empty.

However, I see this

$app = new IlluminateFoundationApplication(
    $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);

This is original /bootstrap/app.php, and it uses $_ENV ??

So
Is /bootstrap/app.php the right place to define constants?
Why is $_ENV empty ?

2

Answers


  1. If you want constants in your application I suggest using classes for this:

    <?php
    
    namespace App;
    
    class Constant
    {
        public const FOO = 'Bar';
    }
    

    And when you want to use it somewhere:

    use AppConstant;
    
    echo Constant::FOO; // Output: Bar
    

    Something like this should work.

    Login or Signup to reply.
  2. You can find out more information about the variabe $_ENV here. It has nothing to do with laravel. You can also see why it might be empty if you check the notes.

    If your $_ENV array is mysteriously empty, but you still see the variables when calling getenv() or in your phpinfo(), check your http://us.php.net/manual/en/ini.core.php#ini.variables-order ini setting to ensure it includes "E" in the string.

    To create constants, the "laravel way" is to create a config file (config/myfile.php) and return an array.

    <?php
    return [
        'constant' => 'test',
    ];
    

    And use it like

    config('myfile.constant'),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search