php - Get env variables names by matching text

404

I have some variables with matching names in .env file as below

    MY_SITE_01=http://www.google.com
    MY_SITE_02=http://www.facebook.com
    MY_SITE_03=http://www.twitter.com

Currently to get the value am using

    env('MY_SITE_01')
    env('MY_SITE_02')
    env('MY_SITE_03')

Is there a way I can do it dynamically or just passing MY_SITE and it gets me all the full names of the variables.

63

Answer

Solution:

There is a way to solve your problem, you can store comma separated websites url into single env variable like shown below :

MY_SITES=http://www.google.com,http://www.facebook.com,http://www.twitter.com

When you need to retrieve its value, you can do :

$mySites  = explode(',', env('MY_SITES')); 
244

Answer

Solution:

You can make amy_site.php file and place it inconfig folder and in the file you could return the data as:

<?php

return [
    'MY_SITE' => [
        'http://www.google.com',
        'http://www.facebook.com',
        'http://www.twitter.com'
    ]
];

Then in your controller or anywhere else you would like, you could use the config helper to retrieve the values.

print_r(config('my_site.MY_SITE'));
603

Answer

Solution:

Add those environments toconfig/app.php as,

'MY_SITES' => [
    'MY_SITE_01' => env('MY_SITE_01', 'http://www.google.com'),
    'MY_SITE_02' => env('MY_SITE_02', 'http://www.facebook.com'),
    'MY_SITE_03' => env('MY_SITE_03', 'http://www.twitter.com')
]

And get it by,

print_r(config('app.MY_SITES'));

This will get value from.env file so no more need to manage multiple places.

People are also looking for solutions to the problem: php - How To seperate Requests from controller for making code cleaner

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.