ihue ihue - 4 months ago 22x
PHP Question

How to access env file from the root of the Laravel Project?

I have a php script locate at the root directory of my laravel project.
I want to access my settings in my .env

I've tried

$dbname = env('DB_DATABASE');
$user = env('DB_USERNAME');
$host = env('DB_HOST');
$pass = env('DB_PASSWORD');

I got

PHP Fatal error: Call to undefined function env()

What is the workaround for that ? Should I include anything to be able to access


If you just want to load your .env config in a separate PHP script, you can do it like this:

require_once "vendor/autoload.php";

This will load your .env config into the $_ENV array.

So now you can access your variables like this:

$dbname      = $_ENV['DB_DATABASE'];
$user        = $_ENV['DB_USERNAME'];
$host        = $_ENV['DB_HOST'];
$pass        = $_ENV['DB_PASSWORD'];

If you really want that env() helper function, just go get that file:

require_once "vendor/laravel/framework/src/Illuminate/Foundation/helpers.php";

And now you can also access env('DB_DATABASE');

Note: this does NOT give you a bootstrapped Laravel environment at all. It's a simple way to grab your .env config variables, but that's it.