You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel中为php artisan down命令新增自定义--time选项参数

自定义Laravel php artisan down 命令新增--time参数实现方案

所有修改均不直接改动vendor目录核心代码,避免Laravel版本更新后自定义逻辑被覆盖

步骤1:生成自定义命令继承原核心Down命令

运行Artisan命令生成自定义命令文件:

php artisan make:command DownCommand

生成的文件路径为 app/Console/Commands/DownCommand.php,修改类继承关系,继承Laravel核心的Down命令:

use Illuminate\Foundation\Console\DownCommand as BaseDownCommand;

class DownCommand extends BaseDownCommand
{
    // 后续逻辑写在这里
}

步骤2:新增--time参数配置与校验

修改自定义DownCommand类的$signature属性,新增--time参数声明,同时重写handle方法加入参数校验:

// 重写命令签名,新增--time参数,默认值为12,单位为小时
protected $signature = 'down
    {--redirect= : The path that users should be redirected to}
    {--render= : The view that should be prerendered for display during maintenance mode}
    {--retry= : The number of seconds after which the request may be retried}
    {--secret= : The secret phrase that may be used to bypass maintenance mode}
    {--status=503 : The status code that should be used when returning the maintenance mode response}
    {--time=12 : 指定laravel-maintenance Cookie的过期时长,单位为小时}';

public function handle()
{
    // 校验--time参数合法性
    $time = (int)$this->option('time');
    if ($time <= 0) {
        $this->error('参数 --time 必须为正整数,不可为0或负数');
        return 1;
    }

    // 调用父类原handle方法执行基础维护模式逻辑
    parent::handle();

    // 输出自定义提示
    $this->info("维护模式已开启,旁路Cookie有效期为{$time}小时");
}

步骤3:修改Cookie有效期逻辑

在Laravel核心逻辑中,维护模式旁路Cookie的默认有效期为24小时,我们需要重写Cookie生成逻辑,将有效期替换为--time参数指定的时长:

如果你使用的是Laravel 9+版本,需要重写bypassResponse方法;Laravel 8及更低版本可直接修改handle方法中的Cookie生成部分

// 重写旁路响应生成方法,自定义Cookie过期时间
protected function bypassResponse(string $secret)
{
    return response()->redirectTo('/')->withCookie(
        'laravel-maintenance',
        $this->getBypassPayload(),
        // 原默认值为1440分钟(24小时),替换为自定义时长转分钟
        (int)$this->option('time') * 60
    );
}

步骤4:注册自定义命令覆盖核心命令

打开 app/Providers/AppServiceProvider.php,在register方法中添加自定义命令注册逻辑,替换Laravel默认的down命令:

public function register()
{
    $this->app->extend('command.down', function () {
        return new \App\Console\Commands\DownCommand();
    });
}

使用示例

  • 开启维护模式,指定Cookie有效期为6小时:php artisan down --time=6
  • 传入非法参数时会直接拦截报错:php artisan down --time=-3 会返回参数错误提示

内容的提问来源于stack exchange,提问作者Amir Naghdi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 07:42:00