This is a quick post on how to enable xdebug for php cli in laravel homestead. Occasionally you will need to use xdebug with laravel artisan cli commands. This post assumes you have laravel up and running and have a general grasp of laravel and homestead / vagrant.
Homestead comes with a nice little utility you can to enable the Laravel homestead xdebug php cli, so firstly ssh into your homestead vagrant machine:
vagrant ssh
Once you have successfully logged in to your laravel homestead virtual machine, you can enable xdebug with the following command:
xon
running php -v
from your laravel homestead bash prompt will give you some output and will show you if xdebug is enabled:
php -v
PHP 8.3.1 (cli) (built: Dec 21 2023 20:12:13) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.3.1, Copyright (c) Zend Technologies
with Zend OPcache v8.3.1, Copyright (c), by Zend Technologies
with Xdebug v3.3.0, Copyright (c) 2002-2023, by Derick Rethans
now that you have established that you have xdebug enabled, it is time for some settings changes. You will need to edit the xdebug ini file that has the xdebug settings. To find the location of that file, run the following from your laravel homestead bash prompt:
php --ini | grep xdebug
On my system it appears as: /etc/php/8.3/cli/conf.d/20-xdebug.ini
I fired up vim
to change some settings:
sudo vim /etc/php/8.3/cli/conf.d/20-xdebug.ini
The settings I added were as follows:
zend_extension=xdebug.so
xdebug.mode = debug
xdebug.discover_client_host = yes
xdebug.start_with_request = yes
xdebug.client_host = 10.0.2.2 // this is the defaul value of the homestead
xdebug.client_port = 9003
xdebug.idekey = VSCODE
xdebug.max_nesting_level = 512
now, exit and save from vim <esc> : w q <enter>
After saving your changes and exiting, you must restart the FPM service. Use the following command to modify the value to match the PHP version you discovered a few steps previous:
sudo service php8.3-fpm restart
You are now ready to use Xdebug from the command line from your Laravel Homestead virtual machine. I use VSCode and the PHP Debug by Felix Becker
plugin. It sets up a listener – you can check here for instructions on setting up xdebug with vscode.
You can initiate by running your CLI artisan command with the following
XDEBUG_SESSION=1 php artisan your_command_here
You should now have vscode pop up and open the file for you to do your step debugging like normal, you can use F10, F12 to step, skip, and add breakpoints etc :)