0
0
Laravelframework~30 mins

.env file and environment variables in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Using .env File and Environment Variables in Laravel
📖 Scenario: You are building a Laravel web application that needs to connect to a database. To keep sensitive information like database credentials safe and separate from your code, you will use a .env file to store environment variables.
🎯 Goal: Learn how to create a .env file with environment variables and access those variables in Laravel configuration and code.
📋 What You'll Learn
Create a .env file with specific environment variables
Add a configuration variable in config/database.php to use the environment variable
Access an environment variable in a Laravel controller
Use the environment variable in a Blade view
💡 Why This Matters
🌍 Real World
Using .env files is a standard way to keep sensitive data like passwords and API keys out of your codebase and easily change configuration per environment (development, testing, production).
💼 Career
Understanding environment variables and .env files is essential for Laravel developers to build secure, configurable applications that work well in different deployment environments.
Progress0 / 4 steps
1
Create the .env file with database variables
Create a .env file in the root of your Laravel project with these exact lines:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=laravel_user
DB_PASSWORD=secret123
Laravel
Need a hint?

The .env file stores key-value pairs for environment variables. Each line should be exactly as shown.

2
Configure database.php to use environment variables
In the config/database.php file, set the 'host' key inside the 'mysql' connection array to use the environment variable DB_HOST by writing:
'host' => env('DB_HOST', '127.0.0.1'),
Laravel
Need a hint?

Use the env() helper function to read environment variables in Laravel config files.

3
Access an environment variable in a Laravel controller
In a Laravel controller method, create a variable called dbUser and assign it the value of the environment variable DB_USERNAME using env('DB_USERNAME').
Laravel
Need a hint?

Use the env() helper inside your controller to get environment variables.

4
Display the environment variable in a Blade view
In a Blade view file, display the value of the variable $dbUser passed from the controller using Blade syntax: {{ $dbUser }}.
Laravel
Need a hint?

Use double curly braces {{ }} in Blade to display variables safely.