Posts Learn Components Snippets Categories Tags Tools new About
/

Laravel Console Command Asking For Confirmation

Learn how to ask confirmation from user to input value when running the console command in Laravel

Created on Aug 05, 2021

214 views

When writing console command in Laravel, sometimes you might need to get the user confirmation before executing an action.

Using "confirm()"
To ask for confirmation from the user, you can make use of the "confirm()" method and pass in the question like below.
if ($this->confirm('Do you wish to continue?')) {
    dd('if confirm returns true then this will get executed');
}

Using auto-complete Options
If you prefer to auto-complete options then you can use "anticipate()" or "choice()" method which accepts the question and suggests possible values of answers.
$answer = $this->anticipate('What is 1 + 2?', [1, 2, 3, 4]);

$name = $this->choice(
    'What is your name?',
    ['Taylor', 'Dayle'],
    $defaultIndex
);

Code Example
To view all of the full code example, do refer below.
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class SayHello extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:say-hello';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Say hello to the user';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        if ($this->confirm('Do you wish to continue?')) {
            $this->info('Hello guys');
        }
    
        $answer = $this->anticipate('What is 1 + 2?', [1, 2, 3, 4]);

        $name = $this->choice(
            'What is your name?',
            ['Taylor', 'Dayle'],
            $defaultIndex
        );

        return 0;
    }
}

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)