How to Create Custom Laravel Artisan Console Commands

Posted on March 2nd, 2023

Laravel is a popular PHP web application framework known for its expressive and elegant syntax, robust features, and ease of use. One of Laravel’s most powerful features is its Artisan command-line interface, which allows developers to interact with their Laravel applications from the terminal. Laravel Artisan comes with many built-in commands, such as creating controllers, models, and migrations, but it also allows developers to create their own custom commands.

Custom Laravel Artisan commands can save developers time and effort by automating repetitive tasks, executing complex processes, and simplifying common tasks. In this article, we will explore how to create custom Laravel Artisan commands step-by-step, including creating basic commands, adding arguments and options, and registering them with the Artisan console. By the end of this article, you will have a solid understanding of how to create custom Artisan commands and how to leverage them in your Laravel applications.

Here are some of the use cases of a custom Laravel Artisan console command.

  1. Data Backup: You can create a custom Artisan command to backup your database automatically. This command can be scheduled to run at regular intervals, ensuring that your data is always backed up and safe.
  2. Generate Test Data: If you need to test your application with a large dataset, you can use a custom Artisan command to generate test data automatically. This can save you time and effort, especially if you need to create a large number of records. You can also use Faker in Laravel to generate fake data for testing. But if you custom use case, You can simply create an artisan command to generate and seed test data in your database.
  3. Social Media Scheduling: You can use a custom Artisan command to schedule social media posts for your application automatically. This can save you time and effort, especially if you need to post updates to multiple social media accounts.
  4. Cleaning Up Old Records: If you have a large database with old records, you can use a custom Artisan command to clean up the database automatically. This can save you time and effort, especially if you need to remove a large number of records.

Overall, custom Laravel Artisan Console Commands can automate many tasks in your application depending on your use case, saving you time and effort while improving your application’s performance and functionality.

As you now have the basic idea where we can use the custom artisan console commands, We can move forward to actually create one command for example.

Creating a Custom Artisan Console Command in Laravel

Creating a basic custom Artisan command in Laravel is a straightforward process. The first step is to navigate to the Laravel project directory. Once you are in your project directory, execute the following command to create a new command.

$ php artisan make:command MyCustomCommand

This command will create a new file named “MyCustomCommand.php” in the “app/Console/Commands” directory of your Laravel application.

When you create a new Artisan console command in Laravel, it generates a skeleton class that defines the basic structure and functionality of the command. In the skeleton class, First of all, You would have to update the signature of your command. Here is the example signature of our example model.

protected $signature = 'my:custom:command';

You can set it according to your use case. You can also update the $description of the command. This description will be displayed in the list of available Artisan console commands.

Lastly, The “handle” method is the main method of the command that is executed when the command is run. This method contains the code that performs the command’s action. The handle method should always return a value of 0 to indicate successful completion. Write the logic of your command in the handle() function of the command. Here is the example of the handle function that only contains a logic to print a line as output. You can modify it and expand it however you want.

public function handle()
{
$this->info('Hello, World!');
}

Our command is ready for execution. To execute the command, Go to the terminal and execute the following command.

$ php artisan my:custom:command

This will output “Hello, World!” in the terminal and command will successfully terminate. You can also pass arguments while executing the command. To do so, You would have to modify the command a bit. Let’s see an example command with argument in brief.

Passing Arguments to Artisan Console Command

To execute command depending on the argument passed, You can modify the $signature of the command to accept the argument. Here is the example signature that takes name as an argument.

protected $signature = 'my:custom:command {name?}';

After that, You can access the the argument in the handle() function of the command. Here is the example handle() function that greets a user with name.

public function handle()
{
$name = $this->argument('name');
$this->info('Hello, ' . $name . '!');
}

To execute this artisan console command, go to the terminal and execute the following.

$ php artisan my:custom:command John

This command will output “Hello, John!” when executed. In this example, we just passed a simple name to the command. In the actual use case, You can pass the ID of the Model, or any unique ID to process the data of a specific Model.

Scheduling an Artisan Console Command

In Laravel, you can use the built-in Task Scheduler to schedule specific Artisan console commands to run automatically at certain intervals. This can be useful for performing tasks like database backups, sending emails, or running periodic maintenance tasks.

To schedule a specific command, Follow the steps given below.

Step 1: Open the “app/Console/Kernel.php” file in your Laravel application. This file contains all the commands you want to schedule in your project.

Step 2: Locate the schedule method, which contains the scheduled tasks for your application.

Step 3: Add a new task to the schedule using the command method. For example, to run the my:custom:command command every hour, you would add the following line of code:

$schedule->command('my:custom:command')->hourly();

Step 4: Now save the “Kernel.php” file and exit your code editor. Once it is saved, run the following command to execute the scheduler.

$ php artisan schedule:run

This command will start the scheduler and execute any scheduled tasks that are due to run.

That’s it! Your custom Artisan command will now be executed automatically at the specified interval. You can modify the schedule as needed by adjusting the parameters of the command method or using other scheduling methods provided by Laravel.

Note: The Laravel Task Scheduler requires that you set up a cron job on the server to run the php artisan schedule:run command every minute. If you are using a VPS, you can simply create a cronjob that runs every minute. If you are on a shared hosting, You can create and manage cronjobs from the web hosting panel you are using.

Conclusion

Creating custom Artisan console commands in Laravel can be a powerful way to extend your application’s functionality and automate common tasks. With just a few lines of code, you can create a new command that performs complex database operations, generates reports, sends emails, and much more.

In this article, we covered the basic steps for creating a new Artisan console command, as well as some creative use cases for custom commands. We also discussed how to schedule a specific Artisan command to run automatically using the Laravel Task Scheduler.

By leveraging the power of Artisan console commands in Laravel, you can save time, increase productivity, and build more robust applications. So go ahead and try creating your own custom command today! If you are facing any issues or errors, Feel free to comment down your error. We will respond with the solution as soon as possible.

Leave a Reply