Laravel serve command doesn't read env variables correctly

664 views Asked by At

I have a Laravel 9.5 and there is an issue with the env variables.

In the project root folder, I have .env file and the content is:

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:key=
APP_DEBUG=true
APP_URL=https://liveurl.com

But when I run it with php artisan serve, the env variables are not read correctly.

I have a form

<form action="{{ route('adminlogin') }}" class="text-left" method="post">

but when it's rendered by the serve command, the action is:

<form action="http://localhost/login" class="text-left" method="post">

which is supposed to be https://liveurl.com/login

I have tried to run all the commands to clear cache, route, view, etc. but nothing helps.

php artisan cache:clear
php artisan view:clear
php artisan route:clear
php artisan route:cache

php artisan config:clear
php artisan config:cache
php artisan event:clear
php artisan event:cache
php artisan optimize:clear

php artisan clear-compiled && php artisan optimize

Can anyone help with this issue?

2

There are 2 answers

3
DreamBold On BEST ANSWER

After much time spent digging into the issue, I finally found out the solution is forcing https for all URLs.

There are many approaches introduced, some of them are:

  1. Adding FORCE_HTTPS=true in the .env file (which didn't work for me)
  2. Adding URL::forceScheme('https') into app\Providers\AppServiceProvider.php file
namespace App\Providers;

use Illuminate\Support\Facades\URL; //--> Need to link this as well
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        URL::forceScheme('https');
    }
}
4
mozart On

Based on your case, it is so weird laravel cannot change the base url dynamically of route() helper. after you change the APP_URL .env and clear the cache config.

Probably, I have some quick solutions for your case.

First, If you want to change your url from the config, just it to config/app.php

 'url' => env('APP_URL', 'https://liveurl.com')

I know, It's not quite good enough to hardcode, but it helps quickly.

Second, you can change the root url from AppServiceProvider, and still get dynamic from .env file.

Add 1 line code in app/Providers/AppServiceProvider.php.

Add this line in boot function:

public function boot(): void
{
    URL::forceRootUrl(config('app.url')); <-- add 
}

don't forget to add the class:

use Illuminate\Support\Facades\URL;

Note: Sometimes the Web Server has to restart