> ## 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 应用中常见配置、环境和基础设施问题的官方包。v0.1.0 于 2026 年 7 月 28 日发布。

每一项诊断（diagnostic）就是一次检查。例如"Laravel 是否可以写入 storage 目录"，并根据多种状态之一进行报告。若可以安全且确定地修复，则会提供自动修复；对于像资源构建失败这类无法自动修复的问题，会给出应对步骤（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`、在生产环境禁用调试模式、将 `.env` 加入 `.gitignore`、创建 `storage:link`、修复 storage 目录的写权限等。

<Info>
  修复功能仅在 CLI 和 agent 输出格式下可用。JSON 与 GitHub 报告格式下，为了不让机器可读的报告修改应用程序，会拒绝 `--fix`。
</Info>

使用 `--bail` 后，会在遇到第一个失败或错误的诊断时停止运行。

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

## 诊断状态

每项诊断会返回以下状态之一。

| 状态       | 含义          | 影响退出码                 |
| -------- | ----------- | --------------------- |
| `pass`   | 检查成功，无问题    | 无                     |
| `notice` | 值得告知开发者的信息  | 无                     |
| `warn`   | 可能无需处理的潜在问题 | 仅在 `--fail-on=warn` 时 |
| `fail`   | 检测到应解决的问题   | 有                     |
| `skip`   | 与当前环境不适用    | 无                     |
| `error`  | 在执行诊断时发生了异常 | 有                     |

默认情况下，出现 `fail` 或 `error` 时会以失败状态退出。可使用 `--fail-on=warn` 让警告也判定为失败，或 `--fail-on=never` 仅报告问题而不影响退出码。

## 诊断选择

可以通过类名、分组、包、包通配符对诊断进行选择或排除。

```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` 队列是合理的默认值，但在生产环境中则意味着队列任务会在 Web 请求内同步执行。基于这类判断，Doctor 会将应用解析为 `local` 或 `production` 两种模式之一。

| 模式           | 预期状态                                      |
| ------------ | ----------------------------------------- |
| `local`      | 开发中。调试模式、`sync` 队列、未缓存的 bootstrap 文件均属正常  |
| `production` | 处理真实流量。调试模式为安全风险，队列应异步执行，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` 的自动修复
* **配置** — 配置文件的加载与缓存可行性、已启用驱动所需的配置值
* **数据库** — 连接可达性、SQLite 文件是否存在、待应用迁移的自动执行
* **缓存 / 队列 / 调度器 / 会话** — 已配置驱动的可达性、非生产环境的 `sync` 队列检测
* **存储** — 默认磁盘的可达性、必需目录的写权限、`storage:link` 是否存在
* **安全** — 调试模式与环境的一致性、`.env` 是否加入 `.gitignore`、Composer 依赖审计

## 自定义诊断的创建

只需继承 `Laravel\Doctor\Diagnostic` 并实现 `check()` 方法，即可创建自定义诊断类。也可以使用 `make:diagnostic` Artisan 命令生成骨架。

```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)');
```

### 诊断辅助工具

许多应用和包会反复编写类似的检查，因此 Doctor 在 `Laravel\Doctor\Support` 命名空间下提供了针对常见模式的辅助工具。

`Configured` 辅助工具用于以防御式方式读取配置值。由于诊断需要能在配置损坏的应用中依然稳定检查而不在报告前抛出异常，这些方法与配置仓库的类型化访问器不同，即使遇到不预期的类型也不会抛出异常。

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

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

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

`ActiveDrivers` 辅助工具会将默认日志通道为 `stack`、mailer 为 `failover` 等包装型驱动解析为实际使用的具体通道或 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` 辅助工具用于格式化附加到 `withDetails()` 的证据信息。`Details::bullets()` 将字符串列表格式化为项目符号，`Details::failures()` 处理带键的失败消息，`Details::processOutput()` 从已完成的进程中选择最有用的输出流。

```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 注册诊断。

```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`。该回调会收到提供修复的失败诊断，返回 `false` 跳过、返回 `true` 应用普通修复，或返回修复选项的值以按该选择应用修复。当修复被应用后，Doctor 会重新运行诊断以反映到报告中。

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

$report->fixes();
```

## 输出格式与 AI 智能体支持

Doctor 默认使用易读的 CLI 输出，也可以选择 JSON 或 GitHub Actions 注解格式。

```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 编码智能体中时，将默认使用与 [Laravel PAO](https://github.com/laravel/pao) 相同规约的智能体优化格式。

```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` 进行修复。在智能体环境外测试该格式时可运行 `AI_AGENT=test php artisan doctor`。

## 小结

`laravel/doctor` 是一款仅需执行 `php artisan doctor` 就能快速排查应用程序配置、环境、基础设施问题的工具。它与 AI 编码智能体的兼容性也很好，会以与 Laravel PAO 相同的规约输出易于智能体解读的结果，因此也非常值得考虑集成到 CI/CD 或基于 AI 智能体的自动修复工作流中。

<Card title="laravel/doctor 仓库" icon="github" href="https://github.com/laravel/doctor">
  源代码与最新信息请见此处。
</Card>


## Related topics

- [Laravel AI SDK](/zh-CN/ai-sdk.md)
- [快速开始 - GitHub Copilot SDK for Laravel](/zh-CN/packages/laravel-copilot-sdk/getting-started.md)
- [Laravel 包开发](/zh-CN/advanced/package-development.md)
- [Service Account 认证 - Google Sheets API for Laravel](/zh-CN/packages/laravel-google-sheets/service-account.md)
- [Artisan 控制台](/zh-CN/artisan.md)
