Search code examples
phpxdebugvscode-debuggerwsl-2laravel-sail

Xdebug with VSCode for Laravel, Sail, WSL2


I'm currently developing a backend application with Laravel Sail. Developing on Windows with VSCode and WSL2 (VSCode with remote WSL mode).

The backend only provide an API for a frontend app. I use Postman to test my backend and would like to set up Xdebug so that I can step debug in VSCode.

It seems the breakpoints are never catched. Although I already did set SAIL_XDEBUG_MODE=develop,debug in my .env file and added a configuration in VSCode launch.json

{
    "name": "Listen for Sail Xdebug",
    "type": "php",
    "request": "launch",
    "port": 9003,
    "pathMappings": {
        "/var/www/html": "${workspaceFolder}"
    },
},

Can anyone help me finding out what is the issue? I already check different similar post though none seems to solve my issue. I always see:

Xdebug: [Step Debug] Could not connect to debugging client. Tried: localhost:9003 (through xdebug.client_host/xdebug.client_port)

I use php:8.2, sail:1.21.2, Laravel 9.52


Solution

  • I finally found out the solution to my issue. Here the problem was launch.json was missing "hostname" key parameter (see https://docs.devsense.com/en/vscode/debug/launch-json apparentrly hostname is required especially on linux system)

    Correct launch.json should like like:

    {
        "name": "Listen for Sail Xdebug",
        "type": "php",
        "request": "launch",
        "port": 9003,
        "pathMappings": {
            "/var/www/html": "${workspaceFolder}"
        },
        "hostname": "localhost"
    },
    

    So to resume. To set up Xdebug in this environment:

    • Add SAIL_XDEBUG_MODE=develop,debug to your .env file
    • Create a configuration launch.json as above
    • Make sure debuging is triggered:
      • With Postman set cookie XDEBUG_SESSION=whatever
      • With browser use debug extension
      • Alternatively set environment variable XDEBUG_SESSION=1 in docker-compose.yml so that debug is triggered for every execution
    version: '3'
    services:
        laravel.test:
            ...
            environment:
                ...
                XDEBUG_MODE: '${SAIL_XDEBUG_MODE:-off}'
                XDEBUG_CONFIG: '${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}'
                XDEBUG_SESSION: 1
            volumes:
                - '.:/var/www/html'
            ...