Custom Artisan command in Laravel

Tram Ho

Currently, with the PHP language, the Laravel framework is one of the most popular frameworks today. There are many projects that use Laravel to deploy the project because of its great features. And the Artisan command is one of those great features. By default, Laravel provides us with some basic commands for our application development. So how can we create the command we want, learn through our article offline

Artisan is built on the Symfony Console component

Some basic commands that the application has provided us:

  • Get all available Artisan commands:

  • When you want help with details about a command you use, arguments and options, we can use the following command:

For example: We want to know the details of the command migrate:

The terminal interface will show us the details of the command to migrate
The commands will usually be saved in the app/Console/Commands folder. However, you can also choose where you save the command as long as your command is loaded by Composer, you can also install the composer load in the composer.json file.
To create a new command we use the command Artisan make:command that laravel has provided us. The new command will create a new class, which is saved in the app/Console/Commands folder. If the application does not have this directory, then after creating a new command using the Artisan make:command , the app/Console/Commands will be created.
After creating we go to kernel.php file to declare the command
We create a new command with the following command:

For details about the make:command and its options we use the command we introduced above:


As in its options, I have added the --command hello:name option to assign the command name. After executing the command to create the command above we open the app/Console/Commands/CustomCommand.php to edit the signature and description of the command we created.
Here I will correct as follows:

fuction handle() will be called when we execute the command. Here I will get the name that we enter when executing the command and display Hello name, This is custom Artisan command .
Then we go to the kernel.php file and add our command:

After performing the above steps, we check the command with the php artisan list
And to see the details of the command we execute: php artisan help hello: name ”

Finally, let’s run the command we created:

The results will show:

Share the news now

Source : Viblo