How to access values ​​from .env in Laravel 5.1 TestCase

In Laravel 5.1 TestCase, the baseUrl is hardcoded. I would like to set it based on the value I set in the .env.

How do I access the .env variables in the TestCase class?

+3


source to share


7 replies


In Laravel 5.2, I replaced the Dotenv :: load call with this ...



$app->loadEnvironmentFrom('.env.testing');

      

0


source


Run Dotenv

to get .env variables in TestCase step



public function createApplication()
{
    $app = require __DIR__.'/../bootstrap/app.php';
    $app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

    Dotenv::load(__DIR__.'/../');
    $this->baseUrl = env('APP_URL', $this->baseUrl);

    return $app;
}

      

+4


source


in Laravel 5.0 TestCase

, I can get a .env variable with the following function.

getenv('APP_VARIABLE');

      

I think it should work with Laravel 5.1 and getenv()

is a PHP function.

+3


source


I can confirm that Christopher Raymond's suggestion above, replace

Dotenv::load call 

      

from

this $app->loadEnvironmentFrom('.env.testing'); 

      

works with Laravel 5.4

See example:

protected $baseUrl = 'http://localhost';

/**
 * Creates the application.
 *
 * @return \Illuminate\Foundation\Application
 */

public function createApplication()
{
    $app = require __DIR__.'/../bootstrap/app.php';

    $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

    $app->loadEnvironmentFrom('.env');
    $this->baseUrl = env('APP_URL', $this->baseUrl);

    return $app;
}

      

+2


source


I have this in my .env file :

APP_URL=http://project.dev

Then I modified the createApplication function in tests /TestCase.php

/**
 * Creates the application.
 *
 * @return \Illuminate\Foundation\Application
 */
public function createApplication()
{
    $this->baseUrl = env('APP_URL', $this->baseUrl);

    $app = require __DIR__ . '/../bootstrap/app.php';

    $app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

    return $app;
}

      

0


source


It turned out that I needed to add the APP_URL key to the phpunit.xml file.

For some reason, I thought that the .env file would be loaded into this process as well, but apparently this is not the case.

0


source


I changed the createApplication function in tests /TestCase.php adding these lines after bootstrap ...-> bootstrap ();

$env = new Dotenv\Dotenv(dirname(__DIR__), '../.env'); 
$env->load();

      

0


source







All Articles