To create and use custom Artisan commands in Laravel, you can follow these steps:
Step 1: Create a new command Run the following command in your terminal at the root of your Laravel project to generate a new command class:
php artisan make:command MyCustomCommand
This will create a new MyCustomCommand
class inside the app/Console/Commands
directory.
Step 2: Modify the command
Open the generated MyCustomCommand
class and update the signature
and description
properties to specify the command name and description:
protected $signature = 'my:customcommand';
protected $description = 'My custom command';
You can also modify the handle
method to define the logic of your command.
Step 3: Register the command
Open the app/Console/Kernel.php
file and add your command class to the commands
array in the protected $commands
property:
protected $commands = [
Commands\MyCustomCommand::class,
];
Step 4: Run the command You can now run your custom command using the Artisan CLI. In the terminal, run:
php artisan my:customcommand
Your custom command will now be executed, and you will see the output as defined in the handle
method.
That's it! You have successfully created and used a custom Artisan command in Laravel. You can add more functionality to your command by adding arguments, options, or even interact with the user via the command line.