skip to Main Content

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

Answers


  1. Chosen as 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 appProvidersAppServiceProvider.php file
    namespace AppProviders;
    
    use IlluminateSupportFacadesURL; //--> Need to link this as well
    use IlluminateSupportServiceProvider;
    
    class AppServiceProvider extends ServiceProvider
    {
        public function boot()
        {
            URL::forceScheme('https');
        }
    }
    

  2. 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 IlluminateSupportFacadesURL;
    

    Note:
    Sometimes the Web Server has to restart

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search