laravel-debugging
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseLaravel Debugging with Xdebug
使用Xdebug调试Laravel应用
When to Apply
适用场景
Activate this skill when:
- Debugging application errors or unexpected behavior
- Investigating 500 errors, exceptions, or fatal errors
- Inspecting variables during code execution
- Tracing request flow through routes, controllers, middleware
- Debugging queue jobs, listeners, or workers
- Analyzing Eloquent query performance and N+1 problems
- Testing API endpoints interactively
- Troubleshooting authentication, authorization, or validation issues
- User mentions: debug, breakpoint, step through, Xdebug, inspect variables, dd(), dump()
在以下场景激活此技能:
- 调试应用错误或异常行为
- 排查500错误、异常或致命错误
- 在代码执行过程中检查变量
- 追踪请求在路由、控制器、中间件中的流转
- 调试队列任务、监听器或工作进程
- 分析Eloquent查询性能及N+1问题
- 交互式测试API端点
- 排查认证、授权或验证相关问题
- 用户提及:debug、breakpoint、step through、Xdebug、inspect variables、dd()、dump()
Prerequisites
前置条件
Before debugging, ensure:
- Xdebug is installed and configured in PHP
- Xdebug is listening on port 9003 (Xdebug 3.x)
- Laravel project has Xdebug enabled in php.ini
- MCP server is running and connected
Verify Xdebug installation:
bash
php -v | grep XdebugConfigure Xdebug in php.ini:
ini
xdebug.mode=debug,develop
xdebug.start_with_request=yes
xdebug.client_host=127.0.0.1
xdebug.client_port=9003调试前请确保:
- PHP中已安装并配置Xdebug
- Xdebug在9003端口监听(Xdebug 3.x版本)
- Laravel项目的php.ini中已启用Xdebug
- MCP服务器已运行并连接
验证Xdebug安装:
bash
php -v | grep Xdebug在php.ini中配置Xdebug:
ini
xdebug.mode=debug,develop
xdebug.start_with_request=yes
xdebug.client_host=127.0.0.1
xdebug.client_port=9003Debugging Features
调试功能
Breakpoint Management
断点管理
Set breakpoints to pause code execution at specific lines:
Add Breakpoint:
Set breakpoint at DealController.php line 88Conditional Breakpoint:
Add breakpoint at UserController.php line 45 if $user->id === 1List Breakpoints:
Show all breakpoints
List active breakpointsRemove Breakpoint:
Remove breakpoint bp_123abc
Clear all breakpoints设置断点以在指定代码行暂停执行:
添加断点:
Set breakpoint at DealController.php line 88条件断点:
Add breakpoint at UserController.php line 45 if $user->id === 1列出断点:
Show all breakpoints
List active breakpoints移除断点:
Remove breakpoint bp_123abc
Clear all breakpointsExecution Control
执行控制
Control code execution flow:
Step Operations:
- Step into - Enter function calls
- Step over - Skip function internals, go to next line
- Step out - Exit current function
- Continue - Run until next breakpoint
Step into the function
Step over to the next line
Step out of this method
Continue execution
Stop debugging控制代码执行流程:
单步操作:
- Step into - 进入函数调用
- Step over - 跳过函数内部,执行到下一行
- Step out - 退出当前函数
- Continue - 运行至下一个断点
Step into the function
Step over to the next line
Step out of this method
Continue execution
Stop debuggingVariable Inspection
变量检查
Inspect variables at breakpoints:
Local Variables:
Show local variables
Inspect variables in current scope
Get all local variablesGlobal Variables:
Show global variables
Display superglobalsEvaluate Expression:
Evaluate $user->id
Check if request->has('token')
Run expression: config('app.debug')Watch Variables:
Watch variable $userData
Add $errors to watch list在断点处检查变量:
局部变量:
Show local variables
Inspect variables in current scope
Get all local variables全局变量:
Show global variables
Display superglobals表达式求值:
Evaluate $user->id
Check if request->has('token')
Run expression: config('app.debug')变量监视:
Watch variable $userData
Add $errors to watch listdd() Capture & Analysis
dd()捕获与分析
Capture and analyze dump output:
Capture the last dump
Show dd() output history
Analyze the most recent dump
Get dump with ID dump_12345The skill provides:
- Non-blocking dump capture
- Historical dump analysis
- Pattern detection (null values, empty arrays, exceptions)
- Laravel-specific insights (Eloquent models, Collections)
捕获并分析dump输出:
Capture the last dump
Show dd() output history
Analyze the most recent dump
Get dump with ID dump_12345该技能提供:
- 非阻塞式dump捕获
- 历史dump分析
- 模式检测(空值、空数组、异常)
- Laravel专属洞察(Eloquent模型、Collections)
Laravel-Specific Debugging
Laravel专属调试
Debugging Controllers
调试控制器
Workflow:
- Set breakpoint in controller method
- Trigger request via browser, Postman, or curl
- Inspect request data, headers, authenticated user
- Step through query execution
- Check validation errors
- Verify response construction
Example:
Set breakpoint at DealController@store line 88
Trigger POST /api/v1/deals with test data
Show me the request payload
Inspect the $deal variable
Step through validation工作流程:
- 在控制器方法中设置断点
- 通过浏览器、Postman或curl触发请求
- 检查请求数据、请求头、已认证用户
- 单步执行查询过程
- 检查验证错误
- 验证响应构建
示例:
Set breakpoint at DealController@store line 88
Trigger POST /api/v1/deals with test data
Show me the request payload
Inspect the $deal variable
Step through validationDebugging Routes
调试路由
List Routes:
Run: php artisan route:list
Show routes matching /api/dealsDebug Route Matching:
Why is this route not matching?
Check middleware stack for this route列出路由:
Run: php artisan route:list
Show routes matching /api/deals调试路由匹配:
Why is this route not matching?
Check middleware stack for this routeDebugging Queue Jobs
调试队列任务
Launch Configuration:
Use "Laravel Queue Worker" configuration in VS Code
Common Issues:
- Job not processing: Check queue connection and worker status
- Job failing: Set breakpoint in job handle() method
- Memory issues: Inspect large datasets or Eloquent relationships
Debugging Steps:
Start queue worker with Xdebug
Set breakpoint in ProcessDealJob handle()
Dispatch job with test data
Inspect job payload
Step through processing启动配置:
在VS Code中使用“Laravel Queue Worker”配置
常见问题:
- 任务未处理:检查队列连接和工作进程状态
- 任务执行失败:在任务的handle()方法中设置断点
- 内存问题:检查大型数据集或Eloquent关联
调试步骤:
Start queue worker with Xdebug
Set breakpoint in ProcessDealJob handle()
Dispatch job with test data
Inspect job payload
Step through processingDebugging Eloquent Queries
调试Eloquent查询
Enable Query Log:
php
DB::enableQueryLog();
// Run queries
dd(DB::getQueryLog());N+1 Query Detection:
Show me the N+1 problem
Analyze Eloquent relationships
Check for eager loading opportunitiesInspect Query Builder:
Evaluate: Deal::where('status', 'active')->toSql()
Show the bindings for this query启用查询日志:
php
DB::enableQueryLog();
// Run queries
dd(DB::getQueryLog());N+1查询检测:
Show me the N+1 problem
Analyze Eloquent relationships
Check for eager loading opportunities检查查询构建器:
Evaluate: Deal::where('status', 'active')->toSql()
Show the bindings for this queryCommon Debugging Workflows
常见调试工作流
Debug 500 Error
调试500错误
- Check Laravel logs:
tail -f storage/logs/laravel.log - Set breakpoint in suspected controller/method
- Trigger the error
- Inspect exception message and stack trace
- Check environment: , database connection
APP_DEBUG - Step through code to identify root cause
- 查看Laravel日志:
tail -f storage/logs/laravel.log - 在疑似问题的控制器/方法中设置断点
- 触发错误
- 检查异常信息和堆栈跟踪
- 检查环境配置:、数据库连接
APP_DEBUG - 单步执行代码以定位根因
Debug Validation Failure
调试验证失败
- Set breakpoint in controller after call
validate() - Inspect object
$errors - Check request data:
$request->all() - Review validation rules in FormRequest
- Verify expected vs actual data types
- 在控制器的调用后设置断点
validate() - 检查对象
$errors - 查看请求数据:
$request->all() - 查看FormRequest中的验证规则
- 验证预期数据类型与实际数据类型是否一致
Debug Authentication Issues
调试认证问题
- Set breakpoint in auth middleware
- Inspect session data
- Check authenticated user:
Auth::user() - Verify token/credentials
- Review guards and providers
- 在auth中间件中设置断点
- 检查会话数据
- 查看已认证用户:
Auth::user() - 验证令牌/凭证
- 查看守卫和提供者配置
Fix N+1 Query Problem
修复N+1查询问题
- Enable query logging
- Set breakpoint in controller/relationship method
- Trigger request
- Inspect query log for repeated queries
- Add eager loading:
User::with('posts')->get() - Verify queries reduced
- 启用查询日志
- 在控制器/关联方法中设置断点
- 触发请求
- 检查查询日志中的重复查询
- 添加预加载:
User::with('posts')->get() - 验证查询数量已减少
Troubleshooting
故障排查
Xdebug Not Connecting
Xdebug无法连接
Symptoms: Breakpoints not hit, "connection refused" errors
Solutions:
- Verify Xdebug is installed:
php -v | grep Xdebug - Check port:
netstat -an | grep 9003 - Verify php.ini configuration
- Restart PHP-FPM or web server
- Check firewall settings
- Ensure Xdebug mode includes "debug"
症状: 断点未触发、出现“connection refused”错误
解决方案:
- 验证Xdebug已安装:
php -v | grep Xdebug - 检查端口:
netstat -an | grep 9003 - 验证php.ini配置
- 重启PHP-FPM或Web服务器
- 检查防火墙设置
- 确保Xdebug模式包含“debug”
Breakpoints Not Hitting
断点未触发
Symptoms: Debugger doesn't stop at breakpoints
Solutions:
- Verify file path mappings in VS Code launch.json
- Check breakpoint line numbers match actual code
- Ensure code is actually being executed
- Verify Xdebug is receiving connection: Check
/tmp/xdebug.log - Try stopping and restarting debugging session
症状: 调试器未在断点处暂停
解决方案:
- 验证VS Code的launch.json中的文件路径映射
- 检查断点行号与实际代码是否匹配
- 确保代码确实被执行
- 验证Xdebug是否接收到连接:查看
/tmp/xdebug.log - 尝试停止并重启调试会话
Variable Inspection Not Working
变量检查失败
Symptoms: Can't see variable values, empty variables
Solutions:
- Ensure execution is paused at breakpoint
- Check variable scope (local vs global)
- Verify Xdebug max_depth and max_data settings
- Try: instead of locals
evaluate '$variableName' - Check for opcache issues: Clear opcache
症状: 无法查看变量值、变量为空
解决方案:
- 确保执行已在断点处暂停
- 检查变量作用域(局部vs全局)
- 验证Xdebug的max_depth和max_data设置
- 尝试使用:替代查看局部变量
evaluate '$variableName' - 检查opcache问题:清除opcache
dd() Blocking Execution
dd()阻塞执行
Symptoms: Script terminates at dd(), can't continue
Solutions:
- Use instead of
dump()to continue executiondd() - Use breakpoint instead of dd()
- Check dump capture is enabled
- Verify write permissions in
/tmp/xdebug-dumps/
症状: 脚本在dd()处终止,无法继续执行
解决方案:
- 使用替代
dump()以继续执行dd() - 使用断点替代dd()
- 确保已启用dump捕获
- 验证目录的写入权限
/tmp/xdebug-dumps/
MCP Server Not Starting
MCP服务器无法启动
Symptoms: Tools not available, connection errors
Solutions:
- Check PHP version: (requires 8.2+)
php -v - Verify required extensions:
php -m | grep -E "xml|sockets" - Check server.php is executable
- Review MCP server logs
- Verify .mcp.json configuration
症状: 工具不可用、出现连接错误
解决方案:
- 检查PHP版本:(要求8.2+)
php -v - 验证所需扩展:
php -m | grep -E "xml|sockets" - 检查server.php是否可执行
- 查看MCP服务器日志
- 验证.mcp.json配置
Best Practices
最佳实践
- Use breakpoints instead of dd() - Non-blocking inspection
- Set specific breakpoints - Avoid stopping everywhere
- Use conditional breakpoints - Only stop when condition is true
- Inspect variables at breakpoints - Better than dump statements
- Clear dump history - Prevent disk space issues
- Enable query logging - For database debugging
- Use watch variables - Track specific values across execution
- Review Xdebug logs - for connection issues
/tmp/xdebug.log
- 使用断点替代dd() - 非阻塞式检查
- 设置精准断点 - 避免全局暂停
- 使用条件断点 - 仅当条件满足时暂停
- 在断点处检查变量 - 优于dump语句
- 清理dump历史 - 防止磁盘空间不足
- 启用查询日志 - 用于数据库调试
- 使用变量监视 - 追踪执行过程中特定值的变化
- 查看Xdebug日志 - 连接问题可查看
/tmp/xdebug.log
Advanced Techniques
高级技巧
Remote Debugging
远程调试
Debug production or staging environments:
- Configure Xdebug to connect to remote IDE
- Set up SSH tunnel for DBGp connection
- Use appropriate IDE key
- Ensure firewall allows Xdebug port
调试生产或预发布环境:
- 配置Xdebug以连接远程IDE
- 为DBGp连接设置SSH隧道
- 使用正确的IDE密钥
- 确保防火墙允许Xdebug端口通行
CLI Debugging
CLI调试
Debug Artisan commands:
php artisan migrate --verboseUse "Laravel Artisan Command" launch configuration
调试Artisan命令:
php artisan migrate --verbose使用“Laravel Artisan Command”启动配置
Test Debugging
测试调试
Debug Pest tests:
- Set breakpoint in test or application code
- Run specific test:
vendor/bin/pest --filter test_name - Use "Laravel Tests (Pest)" configuration
调试Pest测试:
- 在测试或应用代码中设置断点
- 运行指定测试:
vendor/bin/pest --filter test_name - 使用“Laravel Tests (Pest)”配置
Profiling
性能分析
Use Xdebug profiling for performance analysis:
ini
xdebug.mode=profileAnalyze cachegrind files with QCacheGrind or similar tools
使用Xdebug分析性能:
ini
xdebug.mode=profile使用QCacheGrind或类似工具分析cachegrind文件
Quick Reference
快速参考
| Task | Command |
|---|---|
| List breakpoints | |
| Add breakpoint | |
| Step over | |
| Continue | |
| Get locals | |
| Evaluate | |
| Capture dump | |
| 任务 | 命令 |
|---|---|
| 列出断点 | |
| 添加断点 | |
| 单步跳过 | |
| 继续执行 | |
| 获取局部变量 | |
| 表达式求值 | |
| 捕获dump | |
Additional Resources
额外资源
- Xdebug Documentation: https://xdebug.org/docs
- DBGp Protocol: https://xdebug.org/docs/dbgp
- Laravel Debugging: https://laravel.com/docs/12.x/debugging
- VS Code PHP Debug: https://github.com/xdebug/vscode-php-debug
For specific debugging scenarios, see:
- - Xdebug installation guide
references/xdebug-setup.md - - Framework-specific patterns
references/laravel-debugging-patterns.md - - Controller debugging examples
examples/debugging-controller.md - - Queue debugging examples
examples/debugging-queue-job.md
- Xdebug文档: https://xdebug.org/docs
- DBGp协议: https://xdebug.org/docs/dbgp
- Laravel调试文档: https://laravel.com/docs/12.x/debugging
- VS Code PHP调试插件: https://github.com/xdebug/vscode-php-debug
更多特定调试场景请参考:
- - Xdebug安装指南
references/xdebug-setup.md - - 框架专属调试模式
references/laravel-debugging-patterns.md - - 控制器调试示例
examples/debugging-controller.md - - 队列任务调试示例
examples/debugging-queue-job.md