> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Laravel Telescope 實戰技巧

> 介紹在本機開發中最大化 Telescope 效益的實用模式。N+1 檢測、使用 tag 追蹤、自訂 watcher、Dump watcher 的活用等，彙整了官方文件沒有的實用知識。

基本安裝與設定請參考[指南頁面](/zh-TW/telescope)。本頁介紹官方文件沒有記載、於本機開發中實用的活用模式。

Telescope 是**本機開發專用**工具。正式環境的監控請使用 [Laravel Pulse](/zh-TW/pulse) 或 [Laravel Nightwatch](/zh-TW/blog/nightwatch-introduction)。

***

## 系統性地找出 N+1 問題

介紹使用 Telescope 對 N+1 除錯的實用流程。不只單純察覺「同樣的 SELECT 反覆執行」，而是可將修正後的確認一併作為工作流程執行。

```mermaid theme={null}
sequenceDiagram
    participant 瀏覽器
    participant Laravel
    participant Telescope
    participant DB

    瀏覽器->>Laravel: GET /posts
    Laravel->>DB: SELECT * FROM posts (1 個查詢)
    loop 對每個貼文
        Laravel->>DB: SELECT * FROM users WHERE id = ? (N 個查詢)
    end
    Laravel-->>瀏覽器: 回應
    Laravel-->>Telescope: 紀錄查詢歷程
    Note over Telescope: 同樣的 SELECT 敘述 N 次<br>會被加上 slow tag
```

<Steps>
  <Step title="從 Requests 找出慢的請求">
    開啟 `/telescope`，在 Requests 分頁找出執行時間較長的請求。
  </Step>

  <Step title="從 Queries 確認發出的 SQL">
    展開請求詳情，會顯示該請求中執行的所有 SQL 查詢。若類似的 SELECT 敘述重複出現，即為 N+1。
  </Step>

  <Step title="加上 Eager Loading 進行修正">
    在程式碼加上 `with()`，然後重新確認查詢。若查詢數大幅減少即修正完成。
  </Step>
</Steps>

```php theme={null}
// 會產生 N+1 的程式碼
$posts = Post::all();
foreach ($posts as $post) {
    echo $post->user->name; // 對每個貼文都會多發查詢
}

// 用 Eager Loading 解決
$posts = Post::with('user')->get();
```

不需在程式碼加入除錯用的 `dd()` 或 log，這整個流程都能在瀏覽器上完成。

***

## 使用 Tag 追蹤特定請求

Telescope 有**Tag**功能。透過 `Telescope::tag()` 為 entry 附加任意 tag 後，可在儀表板的過濾條件中快速篩選出該 tag 的 entry。

在只想追蹤特定 user ID 或 order ID 相關處理的情境下非常有效。

```php theme={null}
use Laravel\Telescope\IncomingEntry;
use Laravel\Telescope\Telescope;

// 覆寫 TelescopeServiceProvider 的 tags 方法
Telescope::tag(function (IncomingEntry $entry) {
    if ($entry->type === 'request') {
        return array_filter([
            'status:' . $entry->content['response_status'],
            auth()->check() ? 'user:' . auth()->id() : null,
        ]);
    }

    return [];
});
```

如此一來，只要在 `/telescope/requests` 畫面的 Search 輸入 `user:42`，即可只列出 user ID = 42 的請求。

### 自動為模型附加 Tag

在 `TelescopeServiceProvider` 的 `tags` 方法中，可為所有 entry 附加特定的 model ID。

```php theme={null}
// TelescopeServiceProvider
Telescope::tag(function (IncomingEntry $entry) {
    return $entry->tags();
});
```

再進一步在模型上實作 `HasTags` contract，該模型被記錄時就會自動附加 tag。

```php theme={null}
use Laravel\Telescope\Contracts\EntriesRepository;

class Order extends Model implements \Laravel\Telescope\Contracts\HasTags
{
    public function telescopeTags(): array
    {
        return ['order:' . $this->id];
    }
}
```

***

## Dump Watcher 的活用

使用 `dump()` 時，輸出可能混入 HTML 回應，讓 API 除錯變得困難。使用 Telescope 的 Dump watcher 可將 `dump()` 的輸出從瀏覽器回應中分離，改為記錄到儀表板中。

用法很簡單，只要在打開 `/telescope` 的「Dump」分頁狀態下呼叫 `dump()` 即可。

```php theme={null}
// controller
public function index()
{
    $users = User::with('posts')->get();
    dump($users->first()->toArray()); // 會顯示在 Telescope 的 dump 分頁
    return response()->json($users);
}
```

只有在該頁面開啟時才會捕捉，因此可以只在需要時監控。與 `dd()` 不同的是它不會中止應用執行，適合連續發送多個請求的除錯情境。

***

## 透過 Mailpit 整合享受愉快的郵件除錯

將 Mail watcher 與本機 SMTP 伺服器 [Mailpit](https://mailpit.axllent.org/) 結合，可大幅改善郵件開發流程。

```ini theme={null}
# .env
MAIL_MAILER=smtp
MAIL_HOST=127.0.0.1
MAIL_PORT=1025
```

Telescope 的 Mail 分頁可預覽寄出郵件的 HTML 與純文字版本。Mailpit 則能在瀏覽器中確認收到的郵件，並可檢視附件與垃圾郵件分數。

<Tip>
  為避免在測試中不慎將郵件寄到外部，本機請務必使用 Mailpit 或 Mailhog 等本地 SMTP。
</Tip>

***

## 除錯事件與 Listener

事件驅動實作的除錯常常變得棘手。要邊看 log 邊追蹤「事件有發送嗎？」「哪個 listener 被呼叫？」是很繁瑣的。

使用 Telescope 的 Events watcher 可用列表方式確認發出的事件及其 listener。

當 listener 沒有被呼叫時，可以在 Events 分頁確認事件的 entry。

* 事件已發出但沒有顯示 listener → listener 沒有註冊（確認 `EventServiceProvider`）
* 事件本身沒有發出 → 確認 `event()` 的呼叫位置

```php theme={null}
// 本機作為測試替代的確認流程
event(new OrderShipped($order));
// → 在 /telescope/events 確認 OrderShipped 是否顯示
// → 確認 listener SendShippingConfirmation 是否被呼叫
```

***

## 佇列 Job 的除錯

非同步處理的除錯，光看 log 很難找出原因。Telescope 的 Jobs watcher 會紀錄從 job dispatch 到執行結果的資訊。

點擊失敗 job 的 entry 後，可看到 stack trace 與例外訊息。除了 `queue:failed` 資料表外，Telescope 中也能確認，讓失敗原因調查更快速。

```php theme={null}
// 除錯 job 時，改用 sync driver 同步執行較易追蹤
// .env
QUEUE_CONNECTION=sync
```

改為 sync driver 後，job 會在請求內同步執行，job 執行結果也會包含在 Requests watcher 中。

***

## HTTP Client 的除錯

除錯與外部 API 通訊時，HTTP Client Watcher 十分有用。以 `Http::` facade 發出的請求與其回應會被記錄下來。

```php theme={null}
$response = Http::get('https://api.example.com/users');
// → 可在 /telescope/client-requests 確認
```

一眼即可掌握回應內容、狀態碼、執行時間。不用寫 `dd($response->json())` 就能在儀表板中確認。

***

## 總結

| 技巧             | 效果                           |
| -------------- | ---------------------------- |
| N+1 工作流程       | 不需 dd() 就能系統性地發現並修正查詢問題      |
| Tag 標記         | 快速篩選特定使用者、模型的紀錄              |
| Dump watcher   | 不污染 API 回應下確認 dump 輸出        |
| Mailpit 整合     | 讓本機郵件開發更順暢                   |
| Events watcher | 以視覺方式確認 event / listener 的發送 |
| Jobs + sync    | 以同步執行非同步處理來除錯                |
| HTTP Client    | 紀錄與確認外部 API 通訊               |

<Columns cols={2}>
  <Card title="Laravel Telescope 指南" icon="telescope" href="/zh-TW/telescope">
    安裝與 watcher 設定的詳細資訊請參考指南頁面。
  </Card>

  <Card title="Laravel Nightwatch" icon="moon" href="/zh-TW/blog/nightwatch-introduction">
    正式環境監控請使用 Nightwatch。
  </Card>
</Columns>


## Related topics

- [Laravel Nightwatch 入門](/zh-TW/blog/nightwatch-introduction.md)
- [Laravel Telescope](/zh-TW/telescope.md)
- [檔案儲存](/zh-TW/filesystem.md)
- [Laravel Pennant 實務案例](/zh-TW/blog/laravel-pennant.md)
- [用 Laravel 構建 MCP 伺服器](/zh-TW/advanced/mcp-server.md)
