Symfony featured image

How to get .env parameter in Controller in Symfony

This is step by step tutorial on how to get .env parameter in Symfony Controller. This is going to be a short and to the point, it is applicable in Symfony 4 and Symfony 5 both. Let’s start.

How to read .env parameter in Controller ?

It’s a 3 step process,

  1. Define the parameter in .env
  2. Configure parameter in Symfony configuration services.yaml
  3. Read configuration parameter in controller

What is .env file ?

.env is text file which helps to pass some variables to a system environment and make the application independent of hard coding environmental variables being used in an application. using .env different inputs can be passed on dev, staging and production deployment of the environment.

Step 1: Add Key value pair in .env file

In the .env file add a key value pair of parameter, ideally an UPPERCASE_CONVENTION is followed,

.env file is placed in the root of application.

APP_CUSTOM_PARAM="This is custom env parameter"

Step 2: Configure Parameter in services.yaml

In the second step we need to configure a mapping of this parameter in the Symfony.

In application-root/config/services.yaml file configure under parameters key.

# This file is the entry point to configure your own services.
# Files in the packages/ subdirectory configure your dependencies.

# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
    app.custom_param: '%env(APP_CUSTOM_PARAM)%'

Step 3: Read value in Controller using getParameter()

Once this configuration is done, you can use app.custom_param as key to access the value coming from .env file in any controller. For example, following will return the value “This is custom env parameter”

<?php
#application-root/src/Controller
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class HomeController extends AbstractController
{

    /**
     * @Route("/", name="index")
     * */
    public function index(){
        return new Response($this->getParameter('app.custom_param'));
    }
}

When running the application the system will return the value from .env file, result is shown in the image below:

read env param in symfony controller result

Video Tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *