laravel-debugging

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Laravel 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:
  1. Xdebug is installed and configured in PHP
  2. Xdebug is listening on port 9003 (Xdebug 3.x)
  3. Laravel project has Xdebug enabled in php.ini
  4. MCP server is running and connected
Verify Xdebug installation:
bash
php -v | grep Xdebug
Configure 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
调试前请确保:
  1. PHP中已安装并配置Xdebug
  2. Xdebug在9003端口监听(Xdebug 3.x版本)
  3. Laravel项目的php.ini中已启用Xdebug
  4. 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=9003

Debugging Features

调试功能

Breakpoint Management

断点管理

Set breakpoints to pause code execution at specific lines:
Add Breakpoint:
Set breakpoint at DealController.php line 88
Conditional Breakpoint:
Add breakpoint at UserController.php line 45 if $user->id === 1
List Breakpoints:
Show all breakpoints
List active breakpoints
Remove 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 breakpoints

Execution 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 debugging

Variable Inspection

变量检查

Inspect variables at breakpoints:
Local Variables:
Show local variables
Inspect variables in current scope
Get all local variables
Global Variables:
Show global variables
Display superglobals
Evaluate 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 list

dd() 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_12345
The 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:
  1. Set breakpoint in controller method
  2. Trigger request via browser, Postman, or curl
  3. Inspect request data, headers, authenticated user
  4. Step through query execution
  5. Check validation errors
  6. 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
工作流程:
  1. 在控制器方法中设置断点
  2. 通过浏览器、Postman或curl触发请求
  3. 检查请求数据、请求头、已认证用户
  4. 单步执行查询过程
  5. 检查验证错误
  6. 验证响应构建
示例:
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

Debugging Routes

调试路由

List Routes:
Run: php artisan route:list
Show routes matching /api/deals
Debug 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 route

Debugging 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 processing

Debugging 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 opportunities
Inspect 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 query

Common Debugging Workflows

常见调试工作流

Debug 500 Error

调试500错误

  1. Check Laravel logs:
    tail -f storage/logs/laravel.log
  2. Set breakpoint in suspected controller/method
  3. Trigger the error
  4. Inspect exception message and stack trace
  5. Check environment:
    APP_DEBUG
    , database connection
  6. Step through code to identify root cause
  1. 查看Laravel日志:
    tail -f storage/logs/laravel.log
  2. 在疑似问题的控制器/方法中设置断点
  3. 触发错误
  4. 检查异常信息和堆栈跟踪
  5. 检查环境配置:
    APP_DEBUG
    、数据库连接
  6. 单步执行代码以定位根因

Debug Validation Failure

调试验证失败

  1. Set breakpoint in controller after
    validate()
    call
  2. Inspect
    $errors
    object
  3. Check request data:
    $request->all()
  4. Review validation rules in FormRequest
  5. Verify expected vs actual data types
  1. 在控制器的
    validate()
    调用后设置断点
  2. 检查
    $errors
    对象
  3. 查看请求数据:
    $request->all()
  4. 查看FormRequest中的验证规则
  5. 验证预期数据类型与实际数据类型是否一致

Debug Authentication Issues

调试认证问题

  1. Set breakpoint in auth middleware
  2. Inspect session data
  3. Check authenticated user:
    Auth::user()
  4. Verify token/credentials
  5. Review guards and providers
  1. 在auth中间件中设置断点
  2. 检查会话数据
  3. 查看已认证用户:
    Auth::user()
  4. 验证令牌/凭证
  5. 查看守卫和提供者配置

Fix N+1 Query Problem

修复N+1查询问题

  1. Enable query logging
  2. Set breakpoint in controller/relationship method
  3. Trigger request
  4. Inspect query log for repeated queries
  5. Add eager loading:
    User::with('posts')->get()
  6. Verify queries reduced
  1. 启用查询日志
  2. 在控制器/关联方法中设置断点
  3. 触发请求
  4. 检查查询日志中的重复查询
  5. 添加预加载:
    User::with('posts')->get()
  6. 验证查询数量已减少

Troubleshooting

故障排查

Xdebug Not Connecting

Xdebug无法连接

Symptoms: Breakpoints not hit, "connection refused" errors
Solutions:
  1. Verify Xdebug is installed:
    php -v | grep Xdebug
  2. Check port:
    netstat -an | grep 9003
  3. Verify php.ini configuration
  4. Restart PHP-FPM or web server
  5. Check firewall settings
  6. Ensure Xdebug mode includes "debug"
症状: 断点未触发、出现“connection refused”错误
解决方案:
  1. 验证Xdebug已安装:
    php -v | grep Xdebug
  2. 检查端口:
    netstat -an | grep 9003
  3. 验证php.ini配置
  4. 重启PHP-FPM或Web服务器
  5. 检查防火墙设置
  6. 确保Xdebug模式包含“debug”

Breakpoints Not Hitting

断点未触发

Symptoms: Debugger doesn't stop at breakpoints
Solutions:
  1. Verify file path mappings in VS Code launch.json
  2. Check breakpoint line numbers match actual code
  3. Ensure code is actually being executed
  4. Verify Xdebug is receiving connection: Check
    /tmp/xdebug.log
  5. Try stopping and restarting debugging session
症状: 调试器未在断点处暂停
解决方案:
  1. 验证VS Code的launch.json中的文件路径映射
  2. 检查断点行号与实际代码是否匹配
  3. 确保代码确实被执行
  4. 验证Xdebug是否接收到连接:查看
    /tmp/xdebug.log
  5. 尝试停止并重启调试会话

Variable Inspection Not Working

变量检查失败

Symptoms: Can't see variable values, empty variables
Solutions:
  1. Ensure execution is paused at breakpoint
  2. Check variable scope (local vs global)
  3. Verify Xdebug max_depth and max_data settings
  4. Try:
    evaluate '$variableName'
    instead of locals
  5. Check for opcache issues: Clear opcache
症状: 无法查看变量值、变量为空
解决方案:
  1. 确保执行已在断点处暂停
  2. 检查变量作用域(局部vs全局)
  3. 验证Xdebug的max_depth和max_data设置
  4. 尝试使用:
    evaluate '$variableName'
    替代查看局部变量
  5. 检查opcache问题:清除opcache

dd() Blocking Execution

dd()阻塞执行

Symptoms: Script terminates at dd(), can't continue
Solutions:
  1. Use
    dump()
    instead of
    dd()
    to continue execution
  2. Use breakpoint instead of dd()
  3. Check dump capture is enabled
  4. Verify write permissions in
    /tmp/xdebug-dumps/
症状: 脚本在dd()处终止,无法继续执行
解决方案:
  1. 使用
    dump()
    替代
    dd()
    以继续执行
  2. 使用断点替代dd()
  3. 确保已启用dump捕获
  4. 验证
    /tmp/xdebug-dumps/
    目录的写入权限

MCP Server Not Starting

MCP服务器无法启动

Symptoms: Tools not available, connection errors
Solutions:
  1. Check PHP version:
    php -v
    (requires 8.2+)
  2. Verify required extensions:
    php -m | grep -E "xml|sockets"
  3. Check server.php is executable
  4. Review MCP server logs
  5. Verify .mcp.json configuration
症状: 工具不可用、出现连接错误
解决方案:
  1. 检查PHP版本:
    php -v
    (要求8.2+)
  2. 验证所需扩展:
    php -m | grep -E "xml|sockets"
  3. 检查server.php是否可执行
  4. 查看MCP服务器日志
  5. 验证.mcp.json配置

Best Practices

最佳实践

  1. Use breakpoints instead of dd() - Non-blocking inspection
  2. Set specific breakpoints - Avoid stopping everywhere
  3. Use conditional breakpoints - Only stop when condition is true
  4. Inspect variables at breakpoints - Better than dump statements
  5. Clear dump history - Prevent disk space issues
  6. Enable query logging - For database debugging
  7. Use watch variables - Track specific values across execution
  8. Review Xdebug logs -
    /tmp/xdebug.log
    for connection issues
  1. 使用断点替代dd() - 非阻塞式检查
  2. 设置精准断点 - 避免全局暂停
  3. 使用条件断点 - 仅当条件满足时暂停
  4. 在断点处检查变量 - 优于dump语句
  5. 清理dump历史 - 防止磁盘空间不足
  6. 启用查询日志 - 用于数据库调试
  7. 使用变量监视 - 追踪执行过程中特定值的变化
  8. 查看Xdebug日志 - 连接问题可查看
    /tmp/xdebug.log

Advanced Techniques

高级技巧

Remote Debugging

远程调试

Debug production or staging environments:
  1. Configure Xdebug to connect to remote IDE
  2. Set up SSH tunnel for DBGp connection
  3. Use appropriate IDE key
  4. Ensure firewall allows Xdebug port
调试生产或预发布环境:
  1. 配置Xdebug以连接远程IDE
  2. 为DBGp连接设置SSH隧道
  3. 使用正确的IDE密钥
  4. 确保防火墙允许Xdebug端口通行

CLI Debugging

CLI调试

Debug Artisan commands:
php artisan migrate --verbose
Use "Laravel Artisan Command" launch configuration
调试Artisan命令:
php artisan migrate --verbose
使用“Laravel Artisan Command”启动配置

Test Debugging

测试调试

Debug Pest tests:
  1. Set breakpoint in test or application code
  2. Run specific test:
    vendor/bin/pest --filter test_name
  3. Use "Laravel Tests (Pest)" configuration
调试Pest测试:
  1. 在测试或应用代码中设置断点
  2. 运行指定测试:
    vendor/bin/pest --filter test_name
  3. 使用“Laravel Tests (Pest)”配置

Profiling

性能分析

Use Xdebug profiling for performance analysis:
ini
xdebug.mode=profile
Analyze cachegrind files with QCacheGrind or similar tools
使用Xdebug分析性能:
ini
xdebug.mode=profile
使用QCacheGrind或类似工具分析cachegrind文件

Quick Reference

快速参考

TaskCommand
List breakpoints
list_breakpoints()
Add breakpoint
add_breakpoint($file, $line)
Step over
step_over()
Continue
continue_execution()
Get locals
get_locals()
Evaluate
evaluate_expression($expr)
Capture dump
capture_last_dump()
任务命令
列出断点
list_breakpoints()
添加断点
add_breakpoint($file, $line)
单步跳过
step_over()
继续执行
continue_execution()
获取局部变量
get_locals()
表达式求值
evaluate_expression($expr)
捕获dump
capture_last_dump()

Additional Resources

额外资源

For specific debugging scenarios, see:
  • references/xdebug-setup.md
    - Xdebug installation guide
  • references/laravel-debugging-patterns.md
    - Framework-specific patterns
  • examples/debugging-controller.md
    - Controller debugging examples
  • examples/debugging-queue-job.md
    - Queue debugging examples
更多特定调试场景请参考:
  • references/xdebug-setup.md
    - Xdebug安装指南
  • references/laravel-debugging-patterns.md
    - 框架专属调试模式
  • examples/debugging-controller.md
    - 控制器调试示例
  • examples/debugging-queue-job.md
    - 队列任务调试示例