EDDYMENS

Published 6 months ago

How To Store And Access Array Data From Laravel's .env File

Table of contents

Introduction

In Laravel, configuration settings are typically managed using the .env file, which stores key-value pairs that define the behavior of the application. This format works well for most configuration settings. But what if you need to assign a list of values to a single key?

Setting a List

Let's consider a scenario where you need to whitelist multiple domains for Cross-Origin Resource Sharing (CORS) [↗] access in your application.

Step 1: Define the List in .env

To whitelist the domains for CORS, you can list them under a single key in your .env file:

.env Entry

01: ALLOWED_DOMAINS=http://example.com,https://subdomain.example.com,http://localhost:3000

Here, ALLOWED_DOMAINS is the key, and the list of domains separated by commas represents the values.

Step 2: Accessing the List in Your Code

In your application code, you can retrieve and use this list of domains by splitting the string into an array:

Code Implementation

01: <?php 02: 03: $allowedDomains = explode(',', env('ALLOWED_DOMAINS'));

The explode function in PHP splits the string based on the delimiter (, in this case) and returns an array containing each domain.

Conclusion

Laravel also provides an in-built configurations [↗] option beyond .env files.

This allows you to further organize and manage settings by creating a PHP file within a dedicated config directory.

Here is another article you might like 😊 Creating A Browser-based Interactive Terminal (Using XtermJS And NodeJS)