> ## 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 Doctor — 應用診斷工具

> 介紹 laravel/doctor。診斷設定、環境、基礎架構常見問題並自動修復安全項目的 Laravel 官方套件。以 php artisan doctor 指令執行，2026 年 7 月 28 日發佈。

## 前言

[laravel/doctor](https://github.com/laravel/doctor) 是診斷 Laravel 應用中常見設定、環境、基礎架構問題的官方套件。2026 年 7 月 28 日發佈 v0.1.0。

每個診斷（diagnostic）為單一檢查項目。例如檢查「Laravel 是否能寫入 storage 目錄」，並回報多種狀態之一。若能安全且明確地修復，會提供自動修正；若如 asset build 失敗這類無法自動修復的問題，則會提供處理步驟（remediation）。

```bash theme={null}
composer require laravel/doctor --dev
```

## 執行方式

安裝後會註冊 `doctor` Artisan 指令。

```bash theme={null}
php artisan doctor
```

若找出可修復的問題，Doctor 會回報並要求確認是否修復。

```text theme={null}
Storage is writable: The application cannot write to every required storage directory.

 Make the storage directories writable? (yes/no) [yes]
```

若要不需確認直接套用修正，使用 `--fix` 選項。

```bash theme={null}
php artisan doctor --fix
```

標準修正涵蓋建立 `.env`、產生 `APP_KEY`、於正式環境關閉 debug 模式、將 `.env` 加入 `.gitignore`、建立 `storage:link`、修正 storage 目錄寫入權限等在本機明確可完成的修復。

<Info>
  修正功能僅於 CLI 與 agent 輸出格式可用。JSON 與 GitHub 報告格式為避免可機讀報告改動應用，`--fix` 會被拒絕。
</Info>

使用 `--bail` 可在遇到第一個 failed 或 error 的診斷時停止執行。

```bash theme={null}
php artisan doctor --bail
```

## 診斷狀態

每個診斷會回傳以下狀態之一。

| 狀態       | 意義          | 對 exit code 影響       |
| -------- | ----------- | -------------------- |
| `pass`   | 檢查成功、無問題    | 無                    |
| `notice` | 值得告知開發者的資訊  | 無                    |
| `warn`   | 潛在問題，可能不必處理 | 僅 `--fail-on=warn` 時 |
| `fail`   | 找出需解決的問題    | 有                    |
| `skip`   | 目前環境無需檢查    | 無                    |
| `error`  | 執行診斷時發生例外   | 有                    |

預設下若有 `fail` 或 `error` 會以失敗狀態退出。可用 `--fail-on=warn` 讓警告也視為失敗，或 `--fail-on=never` 只回報問題不影響 exit code。

## 選擇診斷

可依類別名稱、群組、套件或套件萬用字元選擇或排除診斷。

```bash theme={null}
php artisan doctor --only=storage

php artisan doctor --only=StorageIsWritable

php artisan doctor --except=laravel/*
```

若發佈設定檔，也可設定持久性的選擇。

```bash theme={null}
php artisan vendor:publish --tag=doctor-config
```

## 環境模式

`sync` 佇列在本機開發是合理預設，但在正式環境代表佇列 Job 會在 Web 請求內同步執行。為此類判斷，Doctor 會將應用解析為 `local` 或 `production` 兩種模式。

| 模式           | 期望狀態                                          |
| ------------ | --------------------------------------------- |
| `local`      | 開發中。debug 模式、`sync` 佇列、未快取的 bootstrap 檔屬正常    |
| `production` | 處理實際流量。debug 模式屬安全風險，佇列應非同步執行，bootstrap 檔應已快取 |

Laravel 標準的 `local`、`production`、`staging` 環境名稱會自動判斷。若使用其他名稱，可在設定檔以群組指派模式。

```php theme={null}
'environments' => [
    'local' => ['local', 'dev'],
    'production' => ['production', 'staging', 'qa'],
],
```

## 標準診斷

Doctor 內建包含下列的診斷套組。

* **環境** — `.env` 是否存在、`APP_KEY`、PHP 版本、必要擴充、時區
* **Composer** — 相依安裝狀態、autoload 最佳化、`composer.lock` 自動修復
* **設定** — 設定檔可否載入與快取、可用 driver 需要的設定值
* **資料庫** — 連線可達性、SQLite 檔案存在、自動套用待處理 migration
* **快取、佇列、排程、Session** — 已設定 driver 的可達性、正式環境以外偵測 `sync` 佇列
* **儲存** — 預設 disk 可達性、必要目錄的寫入權限、`storage:link` 存在
* **安全** — debug 模式與環境一致性、`.env` 是否列在 `.gitignore`、Composer 相依審計

## 自訂診斷

繼承 `Laravel\Doctor\Diagnostic` 並實作 `check()` 方法即可建立自訂診斷類別。也能用 `make:diagnostic` Artisan 指令產生 scaffold。

```bash theme={null}
php artisan make:diagnostic HorizonIsRunning --fixable
```

以下是一個確認 `APP_KEY` 設定，若未設定則自動產生的診斷範例。

```php theme={null}
namespace App\Doctor\Diagnostics;

use Illuminate\Support\Facades\Artisan;
use Laravel\Doctor\Contracts\Fixable;
use Laravel\Doctor\Diagnostic;
use Laravel\Doctor\EnvironmentMode;
use Laravel\Doctor\Results\DiagnosticResult;
use Laravel\Doctor\Results\FixResult;

class ApplicationKeyIsSet extends Diagnostic implements Fixable
{
    public string $name = 'App key is set';

    public string $group = 'environment';

    protected function messages(): array
    {
        return [
            'configured' => 'The application key is configured.',
            'missing' => 'The application key is not configured.',
            'generated' => 'The application key was generated.',
        ];
    }

    public function check(): DiagnosticResult
    {
        $key = config('app.key');

        if (is_string($key) && trim($key) !== '') {
            return $this->pass('configured');
        }

        return $this->fail('missing')->fixable(EnvironmentMode::Local);
    }

    public function fix(DiagnosticResult $result): FixResult
    {
        Artisan::call('key:generate', ['--force' => true]);

        return $this->fixed('generated');
    }
}
```

若修正涉及選項合理，可用 `fixOptions()` 宣告選項。CLI 會以選單方式呈現，選中的值會被傳入 `fix()`。

```php theme={null}
return $this->fail('unreachable')
    ->fixable(EnvironmentMode::Local)
    ->fixOptions(['file' => 'File', 'redis' => 'Redis']);
```

選單最後總會加上「不進行修正」的選項（預設是 `Skip — leave unfixed`）。若「保留目前選擇」的說法更清楚，可指定 `decline` 標籤。

```php theme={null}
->fixOptions(['file' => 'File'], decline: 'Keep Redis (repair it manually)');
```

### 診斷 Helper

由於許多應用或套件會重複撰寫相似的檢查，Doctor 於 `Laravel\Doctor\Support` 命名空間提供常見情境的 helper。

`Configured` helper 會防禦式地讀取設定值。因為診斷必須在應用設定損壞的情況下也能在回報前不拋出例外，因此這些方法與設定 repository 的型別存取器不同，不會因為非預期型別而拋例外。

```php theme={null}
use Laravel\Doctor\Support\Configured;

$connection = Configured::string('queue.default', 'database');

$missing = Configured::missing([
    'services.stripe.key',
    'services.stripe.secret',
]);
```

`ActiveDrivers` helper 會把預設 log channel 為 `stack`、mailer 為 `failover` 等 wrapper driver，解析為實際使用的具體 channel 或 mailer。

```php theme={null}
use Laravel\Doctor\Support\ActiveDrivers;

$channels = ActiveDrivers::logChannels(Configured::string('logging.default', 'stack'));

$mailers = ActiveDrivers::mailers(Configured::string('mail.default', 'log'));
```

`Details` helper 用來整理要附加到 `withDetails()` 的證據。`Details::bullets()` 把字串清單轉為條列、`Details::failures()` 產生帶鍵值的失敗訊息、`Details::processOutput()` 從已完成的 process 選出最有用的輸出串流。

```php theme={null}
use Laravel\Doctor\Support\Details;

Details::bullets(['services.stripe.key', 'services.stripe.secret']);

Details::failures(['media' => 'The disk root is not writable.']);
```

套件也能以相同 API 由 Service Provider 註冊診斷。

```php theme={null}
use Laravel\Doctor\Facades\Doctor;
use Vendor\Package\Diagnostics\HorizonIsRunning;

public function boot(): void
{
    Doctor::diagnostic(HorizonIsRunning::class);
}
```

報告中會顯示診斷的來源套件。

```text theme={null}
[fail] Storage is writable (laravel/doctor): The application cannot write to every required storage directory.
[warn] Horizon is running (laravel/horizon): Horizon is not currently running.
```

## 從程式呼叫

也可以不用 Artisan 指令，直接呼叫 `Doctor::run()`。

```php theme={null}
use Laravel\Doctor\Facades\Doctor;

$report = Doctor::only('security')
    ->except(SomeDiagnostic::class)
    ->run();

if ($report->hasFailures()) {
    // ...
}
```

若程式執行中也要套用修正，可設定 `fixUsing`。Callback 會接收提供修正的失敗診斷，回傳 `false` 表跳過、`true` 表套用一般修正，或回傳修正選項值以該選擇套用修正。修正被套用後 Doctor 會重新執行該診斷以反映到報告。

```php theme={null}
$report = Doctor::fixUsing(
    fn ($outcome) => $outcome->fixRequiresOption() ? false : true,
)->run();

$report->fixes();
```

## 輸出格式與 AI Agent 對應

Doctor 預設輸出易讀 CLI 格式，也可選擇 JSON 或 GitHub Actions annotation 格式。

```bash theme={null}
php artisan doctor --format=json

php artisan doctor --format=github
```

使用 [Laravel Agent Detector](https://github.com/laravel/agent-detector) 偵測到在 Claude Code 或 Cursor 這類 AI 撰碼 Agent 內執行時，預設會採用符合 [Laravel PAO](https://github.com/laravel/pao) 相同規範的 agent 最佳化格式。

```json theme={null}
{"tool":"doctor","result":"failed","diagnostics":27,"failed":1,"warnings":1,"notices":0,"passed":19,"skipped":6,"issues":[{"name":".env file exists","status":"fail","summary":"The application does not have an environment file.","fix":"Run `cp .env.example .env`, then review the copied values.","fixable":true}]}
```

`fixable: true` 的問題可用 `--fix` 再跑一次修正。若想在 Agent 之外試這個格式，可執行 `AI_AGENT=test php artisan doctor`。

## 總結

`laravel/doctor` 只要執行 `php artisan doctor` 就能快速找出應用在設定、環境、基礎架構上的問題。它與 AI 撰碼 Agent 相容，且以與 Laravel PAO 相同規範輸出對 Agent 友善的格式，值得考量納入 CI/CD 或由 AI Agent 自動修復的工作流程。

<Card title="laravel/doctor 儲存庫" icon="github" href="https://github.com/laravel/doctor">
  原始碼與最新資訊請見此處。
</Card>


## Related topics

- [工具](/zh-TW/packages/laravel-copilot-sdk/tools.md)
- [用 Laravel 構建 MCP 伺服器](/zh-TW/advanced/mcp-server.md)
- [Laravel Boost](/zh-TW/boost.md)
- [Laravel 與 AI 開發](/zh-TW/ai.md)
- [Laravel LSP — 以 Language Server Protocol 擴充 IDE 功能](/zh-TW/blog/laravel-lsp-introduction.md)
