Using ngrok with Laravel

by Jeffrey van Rossum

If you like to temporarily expose your local development environment, you can do this with ngrok.

If you use Laravel Valet for development, you already have ngrok available. From your application's folder run the following command in the terminal:

valet share

If you don't use Valet, you'll have to install ngrok. You can do so by following the instructions at ngrok.com

Once you have ngrok installed, we need to do the following to make it work with your local Laravel app.

Open the AppServiceProvider.php file and add the following to the boot method:

public function boot(\Illuminate\Http\Request $request)
    {
        if (!empty( env('NGROK_URL') ) && $request->server->has('HTTP_X_ORIGINAL_HOST')) {
            $this->app['url']->forceRootUrl(env('NGROK_URL'));
        }

        // other code
}

After you’ve done that, run the following command in your terminal. Make sure the URL is replaced with the local URL your Laravel app uses.

ngrok http -host-header=rewrite laravel-site.test:80

You’ll get a forwarding URL back. This URL, typically looking something like abc123.ngrok.io.

In your .env file, specify the property NGROK_URL with the URL you have received from ngrok.

You might need to empty your app’s cache (from the terminal):

php artisan config:clear
php artisan cache:clear
php artisan view:clear
php artisan route:clear
This post was last modified 7 September 2020
Did you like this post?

If you sign up for my newsletter, I can keep you up to date on more posts like this when they are published.