How to make Custom Artisan Command in Laravel
Custom Artisan commands are a useful feature of Laravel that allow you to define your own command-line commands for tasks such as seeding the database, generating code, or running scheduled jobs. Here’s how to create a custom Artisan command in Laravel:
- Open a terminal window and navigate to your Laravel project directory.
- Run the
php artisan make:commandcommand followed by the name of your command. For example, if your command is called “send-emails”, you would run
php artisan make:command SendEmails. This will create a new command class in the
- Open the command class that was just created and define the signature and description of your command. The signature is the name of the command as it will be typed in the terminal, and the description is a brief explanation of what the command does. You can define these by setting the
$descriptionproperties at the top of your command class.
- In the
handlemethod of your command class, define the code that should be executed when the command is run. This is where you can add any logic or code that you want to be executed when the command is called.
- To register your command with Artisan, open the
app/console/Kernel.phpfile and add your command class to the
- Run the
php artisan listcommand to see a list of all available Artisan commands, including your custom command. You can now run your custom command by typing
php artisan [command-name]in the terminal.
By following these steps, you can easily create custom Artisan commands in Laravel to automate tasks and streamline your workflow.