garrettmassey's avatar

How do I leverage Laravel Prompt's default "cancel" behavior?

I'm working on implementing a command line feature for one of our internal apps, and I really like the way Laravel Prompts handles the CTRL + C cancellation of forms, changing the colors, adding the nice red "Cancelled" with the icon. What I'd love to do is leverage that, so that, for example, I can use the "select" prompt to ask the user to select a specific module, and give "cancel" as one of the options, and if the user selects "cancel" then the command treats it like a CTRL + C cancel and Prompts takes care of the rendering.


protected function selectModule(): string
    {
        $modulesPath = base_path('modules');

        // Get all module directories
        $modules = Module::all()->pluck('name')->toArray();
        $module = select(
            label: 'What role should the user have?',
            options: [...$modules, 'Cancel'],
            default: 'Owner',
            hint: 'The role may be changed at any time.'
        );

        if ($module === 'Cancel') {
            //make it cancel like Prompts does
        }
        return $module;
}
0 likes
1 reply
LaryAI's avatar
Level 58

To leverage Laravel Prompt's default "cancel" behavior when a user selects "Cancel" from your options, you can manually throw an exception that mimics the behavior of a CTRL + C cancellation. Laravel's console commands typically handle CTRL + C by throwing a Symfony\Component\Console\Exception\RuntimeException. You can use this to simulate the cancellation.

Here's how you can modify your selectModule method to achieve this:

use Symfony\Component\Console\Exception\RuntimeException;

protected function selectModule(): string
{
    $modulesPath = base_path('modules');

    // Get all module directories
    $modules = Module::all()->pluck('name')->toArray();
    $module = select(
        label: 'What role should the user have?',
        options: [...$modules, 'Cancel'],
        default: 'Owner',
        hint: 'The role may be changed at any time.'
    );

    if ($module === 'Cancel') {
        // Simulate a CTRL + C cancellation
        throw new RuntimeException('Command cancelled.');
    }

    return $module;
}

By throwing a RuntimeException, you can simulate the cancellation behavior, and Laravel's console will handle it similarly to a CTRL + C event, including the display of the cancellation message.

Please or to participate in this conversation.