Debug Laravel Applications With VSCode and Xdebug

Written by in Laravel on 2~3 minutes
Debug Laravel Applications With VSCode and Xdebug

If you have been using Xdebug to debug your PHP applications, you might have missed Xdebug in your Laravel applications. Usually, the Xdebug setup process is little bit cumbersome and you will have to install browser plugins, change Xdebug configurations and fix some other unintended issues to get Xdebug work properly with Laravel. However, thanks to Laravel Sail, believe me, now it has became a really easy task. In this post, I’ll explain how to setup Xdebug within few minutes.

First, go to extensions section of VSCode or simply use the [Ctrl]+[Shift]+[X] shortcut. Then search for “PHP Debug” and install it. If you need, you can also press [Ctrl]+[P] and type ext install xdebug.php-debug and hit enter key to install the PHP Debug plugin. Also, make sure it is active.

After that, create a new directory called .vscode in your Laravel project directory. Inside of that, create a file called launch.json and paste the following code into it.

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for Xdebug",
            "type": "php",
            "request": "launch",
            "log": false,
            "pathMappings": {
                "/var/www/html": "${workspaceFolder}"
            },
            "ignore": [
                "**/vendor/**/*.php"
            ],
            "port": 9003
        }
    ]
}

Then open your .env file and add the following lines at the end of it.

SAIL_XDEBUG_MODE=develop,debug,coverage
SAIL_XDEBUG_CONFIG='start_with_request=yes client_host=host.docker.internal idekey=VSCODE'

Now no need to rebuild the Laravel Sail Docker image, just restart Laravel Sail and press the [F5] key. You should see a toolbar something similar to the following.

PHP Xdebug VSCode Toolbar

If you could see it, you should be ready to debug your Laravel application. Open a PHP file that you need to debug, add a breakpoint and visit the related page to execute the required line like below.

PHP Xdebug VSCode Debugging Interface

Written By

A web guy. Currently, he works as a backend developer. In his free time, he writes about PHP, Laravel, WordPress and NodeJS.