By default, Laravel framework has three environments: local
, production
and testing
. This tutorial provides 2 methods how to get environment name in Laravel 9 application.
The APP_ENV
variable allows to define the environment in which the application runs. It can be specified in the .env
file.
APP_ENV=local
If .env
has been changed, don't forget to clear configuration cache.
php artisan config:cache
Method 1 - 'App' facade
The App
facade provides the environment
method to get environment name.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\App;
class TestController extends Controller
{
public function index(): Response
{
$env = App::environment();
return new Response($env);
}
}
Method 2 - 'app' helper function
The app
helper function allows getting an instance of the Application
class, which provides the environment
method for retrieving environment name.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Response;
class TestController extends Controller
{
public function index(): Response
{
$env = app()->environment();
return new Response($env);
}
}
Leave a Comment
Cancel reply