Laravel 9 Create Custom Artisan Command Example Tutorial

Last Updated on by in Laravel

In this step-by-step tutorial, we’ll guide you through creating a custom Artisan command in Laravel.

Artisan commands streamline development tasks and improve productivity by providing an interface for executing specific operations. In this example, we’ll create a command to generate test user data and insert it into the database.

We’ll begin by defining the command class, generateUserData, in the App\Console\Commands namespace. Within this class, you’ll declare the command signature, description, and handle method.

The handle method is the core function that executes the command, where you retrieve the count argument and iterate to generate the specified number of users using the Eloquent factory.

By creating the command create:generate-users, you can specify the number of test users you want to generate and add to your database. This is particularly useful for testing purposes or when populating your application with sample data.

By the end of this guide, you’ll have a solid understanding of how to create and use custom Artisan commands in Laravel to automate tasks and improve your development workflow.

How to Make Custom Artisan Command in Laravel

  • Step 1: Download New Laravel App
  • Step 2: Connect Laravel to Database
  • Step 3: Generate Artisan Command
  • Step 4: Create Artisan Command
  • Step 5: Run Artisan Command

Download New Laravel App

The composer provides handy way to install laravel app, open terminal and execute the suggested command to create a fresh Laravel project from scratch.

composer create-project laravel/laravel --prefer-dist laravel-demo

Get into the laravel app.

cd laravel-demo

Connect Laravel to Database

Next, you have to connect the laravel app to database, it can be done by inserting the database name, username and password in the .env file.

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Before generating the user data, you have to run the outstanding migrations, hence execute the migrate Artisan command.

php artisan migrate

Generate Artisan Command

To create a new command, you may use the make:command Artisan command. This command will generate a new command class inside the app/Console/Commands folder.

Fret not if this folder does not exist in your app – it will be created when you invoke the make:command Artisan command.

Open the terminal window, type command and hit enter to create a new artisan command.

php artisan make:command generateUserData

Create New Laravel Artisan Command

To build a new Laravel Artisan command, you have to go to the app/Console/Commands/generateUserData.php file; in this file, you have to define the command name to the $signature variable.

Here generate-users is the command name, and {count} is the variable that refers to the number of the records to be generated.

The handle() function holds the logic to run the factory tinker command, manifesting the records in the database.

After that you need to update app/Console/Commands/generateUserData.php file with the following code.

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\User;

class generateUserData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'create:generate-users {count}';
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Creates test user data and insert into the database.';
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $usersData = $this->argument('count');
        for ($i = 0; $i < $usersData; $i++) { 
            User::factory()->create();
        }          
    }
}

Run Custom Artisan Command

In the final step, we have to type the custom artisan command on the console screen and execute it to generate the users’ data into the database.

You may change the total number of the records as per your choice whereas the command remains the same.

php artisan create:generate-users 250

Laravel Create Custom Artisan Command Tutorial

Conclusion

Creating a custom Artisan command in Laravel can significantly boost your productivity and streamline development tasks.

With this guide, you now know how to create test user data using the command line, opening up possibilities for generating various data types and automating tasks.

Age calculator tool

🎂✨ Discover your age in detail and with countdown to your next birthday with fun facts! 🎈🎉

Calculate your age now!
Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.