Home / Snippets / Laravel Console Command Asking For Confirmation
Laravel Console Command Asking For Confirmation cover

Laravel Console Command Asking For Confirmation

746

2 years ago

0 comments

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;
    }
}

notion avatar

Ahmad Aziz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this