phplaravelenvironment-variablesphpdotenv

Laravel 5.2 dynamic environment variables based on user


In my .env file I have two variables

App_id: 12345
App_secret: abc123

But I'm wondering if there's a way so that if user userNo2 logs in then it would instead use

App_id: 45678
App_secret: abc456

Is there a way to have if/else functionality in the env file based on the user?


Solution

  • Yes it is possible, but not in the .env file. Instead, you can move your logic to middleware:

    Step 1: Add default values to the application config

    Open your app/config/app.php and add your default values to the existing array.

    <?php
    
    return [
        'APP_ID' => '45678',
        'APP_SECRET' => 'abc456',
        ...
    ];
    

    Step 2: Create a new Middleware

    php artisan make:middleware SetAppConfigForUserMiddleware

    Edit the file to look like this:

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\Facades\App;
    use Illuminate\Support\Facades\Config;
    
    class SetAppConfigForUserMiddleware
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
             $authorizedUser = Auth::user();
    
            if (!App::runningInConsole() && !is_null($authorizedUser)) {
                Config::set('app.APP_ID', 'appidOfUser' . $authorizedUser->name);
                Config::set('app.APP_SECRET', 'appsecretOfUser' . $authorizedUser->email);
            }
            return $next($request);
        }
    }
    

    Step 4: Run your middleware

    If you need to set this config for the user in all the web routes you can add to the $middlewareGroups array in app/Http/kernel.php. This will apply the middleware to all the routes inside web.php.

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            ...
            \App\Http\Middleware\SetAppConfigForUserMiddleware::class,        
        ],
    

    Step 5: Testing

    For example, my Auth:user()->name is "John" and my Auth:user()->email is "john@example.com"

    If you put this in your resources/views/home.blade.php

    App Id Of User <code>{{config('app.APP_ID')}}</code>
    App Secret Of User <code>{{config('app.APP_SECRET')}}</code>
    

    The result will be appidOfUserJohn and appsecretOfUserjohn@example.com.