LoginSignup
0
0

Laravel 本番環境で自作コマンドを実行するときに確認メッセージを表示させる

Last updated at Posted at 2023-06-25

本番環境で自作コマンド実行時に確認メッセージを表示させたい

本番環境でマイグレーションを実行しようとすると本番環境で本当に実行して良いかの確認メッセージが表示されます。

$ php artisan migrate

                          APPLICATION IN PRODUCTION.

  Do you really wish to run this command? (yes/no) [no]

これと同じことを自作のコマンドに追加します。

環境

  • PHP: 8.2.7
  • Laravel: 10.13.5

実装

$ php artisan make:command SampleCommand
app/Console/Commands/SampleCommand.php
<?php

declare(strict_types=1);

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;

final class SampleCommand extends Command
{
    use ConfirmableTrait;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:sample-command
        {--force : Force the operation to run when in production}
    ';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    public function handle(): int
    {
        if (! $this->confirmToProceed()) {
            $this->comment('Stop sample command');

            return self::FAILURE;
        }

        $this->info('Execute sample command');

        return self::SUCCESS;
    }
}
  • use ConfirmableTrait; 確認メッセージを表示するためのトレイト
  • {--force : xxx} forceオプションの受け取り
  • $this->confirmToProceed() 確認メッセージを表示

この3点を実装すれば確認メッセージを表示できます。

使い方

$ php artisan tinker --execute="echo config('app.env')"
production

production 環境の時にコマンドを実行すると下記のように確認メッセージが表示されます。

$ php artisan app:sample-command

                          APPLICATION IN PRODUCTION.
  Do you really wish to run this command? (yes/no) [no]
❯ n


   WARN  Command canceled.

Stop sample command

--force オプションを渡すと確認メッセージを表示することなくコマンドを実行できます。

$ php artisan app:sample-command --force
Execute sample command
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0