laravel-debugging-prompts

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Debugging Prompts

调试提示词

Debugging with AI requires complete information. Missing context means generic suggestions that don't solve your specific problem.
使用AI进行调试需要提供完整的信息,缺失上下文会导致你得到无法解决具体问题的通用建议。

Error Messages and Stack Traces

错误信息与堆栈跟踪

Incomplete

不完整示例

"Getting an error in the payment controller"
"支付控制器出现报错"

Complete

完整示例

"Getting error when processing payment:
Error:
Illuminate\Database\QueryException: SQLSTATE[23000]:
Integrity constraint violation: 1452 Cannot add or update a child row:
a foreign key constraint fails (`app`.`payments`, CONSTRAINT `payments_order_id_foreign`
FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE)
Stack trace:
#0 app/Services/PaymentService.php(45): Payment::create()
#1 app/Http/Controllers/PaymentController.php(28): PaymentService->process()
#2 vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54)
Context:
  • Laravel 11.x, MySQL 8.0
  • Happens when order_id doesn't exist in orders table
  • Payment data:
    ['order_id' => 999, 'amount' => 5000, 'status' => 'pending']
  • Order 999 doesn't exist in database"
Why it works: Complete error, stack trace, context, and the specific data causing the issue.
"处理支付时出现报错:
错误信息:
Illuminate\Database\QueryException: SQLSTATE[23000]:
Integrity constraint violation: 1452 Cannot add or update a child row:
a foreign key constraint fails (`app`.`payments`, CONSTRAINT `payments_order_id_foreign`
FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE)
堆栈跟踪:
#0 app/Services/PaymentService.php(45): Payment::create()
#1 app/Http/Controllers/PaymentController.php(28): PaymentService->process()
#2 vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54)
上下文:
  • Laravel 11.x, MySQL 8.0
  • 当order_id不存在于orders表时会触发该错误
  • 支付数据:
    ['order_id' => 999, 'amount' => 5000, 'status' => 'pending']
  • 订单999不存在于数据库中"
为什么有效: 提供了完整的报错信息、堆栈跟踪、上下文,以及导致问题的具体数据。

Expected vs Actual Behavior

预期与实际行为对比

Vague

模糊表述

"The API isn't returning the right data"
"API返回的数据不对"

Specific

清晰表述

"Product API returning incorrect data:
Expected behavior:
json
{
  "data": {
    "id": 1,
    "name": "Widget",
    "price": "29.99",
    "category": {
      "id": 5,
      "name": "Tools"
    }
  }
}
Actual behavior:
json
{
  "data": {
    "id": 1,
    "name": "Widget",
    "price": 2999,
    "category": null
  }
}
Issues:
  1. Price is in cents (2999) instead of formatted dollars ("29.99")
  2. Category is null even though product has category_id = 5
Code:
php
// ProductController@show
return new ProductResource($product);
Product has
category_id = 5
in database, but relationship not loading."
Why it works: Shows exact expected vs actual output, identifies specific issues, includes relevant code.
"商品API返回数据异常:
预期行为:
json
{
  "data": {
    "id": 1,
    "name": "Widget",
    "price": "29.99",
    "category": {
      "id": 5,
      "name": "Tools"
    }
  }
}
实际行为:
json
{
  "data": {
    "id": 1,
    "name": "Widget",
    "price": 2999,
    "category": null
  }
}
问题:
  1. 价格单位为分(2999)而不是格式化后的美元("29.99")
  2. 即使商品的category_id = 5,返回的category仍为null
代码:
php
// ProductController@show
return new ProductResource($product);
数据库中商品的
category_id = 5
,但关联关系没有加载。"
为什么有效: 展示了精确的预期输出和实际输出,明确了具体问题,同时包含了相关代码。

Log Entries and State

日志条目与运行状态

Insufficient

信息不足的表述

"Something's wrong with the queue"
"队列出问题了"

Sufficient

信息充足的表述

"Job failing in queue:
Log entries:
[2024-01-15 10:30:15] local.ERROR: Job failed: ProcessOrderJob
{"order_id":123,"exception":"Stripe\\Exception\\InvalidRequestException:
No such customer: cus_invalid","attempts":3}

[2024-01-15 10:30:15] local.INFO: Order state before job
{"id":123,"status":"pending","stripe_customer_id":"cus_invalid"}
Job code:
php
public function handle()
{
    $customer = $this->stripe->customers->retrieve(
        $this->order->stripe_customer_id
    );
    // ...
}
State:
  • Order 123 has
    stripe_customer_id = "cus_invalid"
  • Customer doesn't exist in Stripe
  • Job has retried 3 times, now in failed_jobs table
  • Using Laravel 11.x with Horizon"
Why it works: Includes logs, state information, relevant code, and context about retries.
"队列中的任务执行失败:
日志条目:
[2024-01-15 10:30:15] local.ERROR: Job failed: ProcessOrderJob
{"order_id":123,"exception":"Stripe\\Exception\\InvalidRequestException:
No such customer: cus_invalid","attempts":3}

[2024-01-15 10:30:15] local.INFO: Order state before job
{"id":123,"status":"pending","stripe_customer_id":"cus_invalid"}
任务代码:
php
public function handle()
{
    $customer = $this->stripe->customers->retrieve(
        $this->order->stripe_customer_id
    );
    // ...
}
状态:
  • 订单123的
    stripe_customer_id = "cus_invalid"
  • 该客户不存在于Stripe中
  • 任务已经重试3次,现在位于failed_jobs表中
  • 使用Laravel 11.x + Horizon"
为什么有效: 包含了日志、状态信息、相关代码,以及重试相关的上下文。

Hypotheses and Evidence

假设与证据

Weak

弱论证表述

"I think it's a caching issue"
"我觉得是缓存的问题"

Strong

强论证表述

"Suspect Redis cache is stale:
Hypothesis: Product prices are cached but not invalidating on update.
Evidence:
  1. Updated product price in database:
    UPDATE products SET price = 3999 WHERE id = 1
  2. Database shows:
    SELECT price FROM products WHERE id = 1
    3999
  3. API returns old price:
    GET /api/products/1
    "price": "29.99"
  4. After
    php artisan cache:clear
    , API returns correct price:
    "price": "39.99"
Caching code:
php
public function show(Product $product)
{
    $cached = Cache::remember("product.{$product->id}", 3600, function () use ($product) {
        return new ProductResource($product);
    });
    return $cached;
}
Problem: Cache key doesn't invalidate when product updates. Need cache invalidation in ProductObserver or remove caching from show method."
Why it works: Clear hypothesis, concrete evidence, relevant code, proposed solution.
"怀疑Redis缓存过期:
假设: 商品价格被缓存,但更新时没有失效。
证据:
  1. 已在数据库中更新商品价格:
    UPDATE products SET price = 3999 WHERE id = 1
  2. 数据库查询结果:
    SELECT price FROM products WHERE id = 1
    3999
  3. API返回旧价格:
    GET /api/products/1
    "price": "29.99"
  4. 执行
    php artisan cache:clear
    后,API返回正确价格:
    "price": "39.99"
缓存代码:
php
public function show(Product $product)
{
    $cached = Cache::remember("product.{$product->id}", 3600, function () use ($product) {
        return new ProductResource($product);
    });
    return $cached;
}
问题: 商品更新时缓存key没有失效,需要在ProductObserver中添加缓存失效逻辑,或者从show方法中移除缓存。"
为什么有效: 假设清晰,证据具体,包含相关代码,还给出了提议的解决方案。

Attempted Solutions

已尝试的解决方案

Unhelpful

无效表述

"I tried some things but nothing worked"
"我试了一些方法都没用"

Helpful

有效表述

"Attempted solutions and results:
Attempt 1: Added eager loading
php
$products = Product::with('category')->get();
Result: Still getting N+1 queries. Debugbar shows 101 queries (1 for products, 100 for categories).
Attempt 2: Used
load()
after fetching
php
$products = Product::all();
$products->load('category');
Result: Same issue, still 101 queries.
Attempt 3: Checked relationship definition
php
// In Product model
public function category()
{
    return $this->belongsTo(Category::class);
}
Result: Relationship looks correct. Foreign key
category_id
exists in products table.
Current state: Eager loading syntax seems correct but not working. Using Laravel 11.x. What am I missing?"
Why it works: Shows what was tried, exact code used, results observed, helps avoid suggesting already-tried solutions.
"已尝试的解决方案和结果:
尝试1: 添加预加载
php
$products = Product::with('category')->get();
结果: 仍然存在N+1查询问题,Debugbar显示有101条查询(1条查商品,100条查分类)。
尝试2: 取数后使用
load()
php
$products = Product::all();
$products->load('category');
结果: 问题相同,仍然有101条查询。
尝试3: 检查关联关系定义
php
// In Product model
public function category()
{
    return $this->belongsTo(Category::class);
}
结果: 关联关系看起来正确,products表中存在外键
category_id
当前状态: 预加载语法看起来正确但没有生效,使用的是Laravel 11.x,我漏掉了什么?"
为什么有效: 展示了你已经尝试过的方案、使用的具体代码、观察到的结果,避免AI推荐你已经试过的解决方案。

Debugging Templates

调试模板

Template: Error Report

模板:错误报告

**Error:** [Full error message]
**Stack trace:** [Complete stack trace]
**File/Line:** [Where error occurs]
**Context:** [Laravel version, packages, environment]
**Data:** [Input data causing error]
**Expected:** [What should happen]
**错误:** [完整错误信息]
**堆栈跟踪:** [完整堆栈跟踪]
**文件/行号:** [错误发生的位置]
**上下文:** [Laravel版本、依赖包、运行环境]
**数据:** [触发错误的输入数据]
**预期:** [应该发生的行为]

Template: Unexpected Behavior

模板:异常行为报告

**Expected:** [Describe expected behavior with example]
**Actual:** [Describe actual behavior with example]
**Code:** [Relevant code snippet]
**State:** [Database state, variable values]
**Environment:** [Laravel version, Sail/host, packages]
**预期:** [描述预期行为并附示例]
**实际:** [描述实际行为并附示例]
**代码:** [相关代码片段]
**状态:** [数据库状态、变量值]
**环境:** [Laravel版本、Sail/主机环境、依赖包]

Template: Performance Issue

模板:性能问题报告

**Problem:** [Describe slow operation]
**Metrics:** [Response time, query count, memory usage]
**Query log:** [Slow queries from Debugbar/Telescope]
**Code:** [Code causing performance issue]
**Dataset size:** [Number of records involved]
**Attempted:** [Optimizations already tried]
**问题:** [描述慢操作的表现]
**指标:** [响应时间、查询数量、内存占用]
**查询日志:** [来自Debugbar/Telescope的慢查询]
**代码:** [导致性能问题的代码]
**数据集大小:** [涉及的记录数量]
**已尝试:** [已经试过的优化方案]

Quick Reference

快速参考

Debug effectively with AI:
  • Complete errors - Full message, stack trace, file/line
  • Show both sides - Expected vs actual behavior
  • Include logs - Error logs, info logs, state dumps
  • Share evidence - Database queries, API responses, variable dumps
  • Document attempts - What you tried, exact code, results
  • Provide context - Laravel version, environment, packages
More information = faster solutions. When debugging, over-communicate.
使用AI高效调试的要点:
  • 完整报错信息 - 完整的错误信息、堆栈跟踪、文件/行号
  • 对比双端行为 - 预期行为 vs 实际行为
  • 包含日志 - 错误日志、信息日志、状态转储
  • 提供证据 - 数据库查询结果、API响应、变量转储
  • 记录尝试 - 你试过什么方案、具体代码、得到的结果
  • 提供上下文 - Laravel版本、运行环境、依赖包
信息越多,解决问题的速度越快。调试时请尽可能多提供相关信息。