Archive

Posts Tagged ‘artisan’

Laravel 9 Create Custom Artisan Command

January 7, 2023 Leave a comment

Artisan is the command-line interface that is included with Laravel. It is driven by the Symfony Support component.

Today we will learn how to create a custom artisan command in the Laravel application and how to use the custom laravel artisan command.

Following command will generate a file under ‘app\Console\Commands\’ with name CreateUsers.php

php artisan make:command CreateUsers

Here is the file code

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class CreateUsers extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:name';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $numberOfUsers = $this->argument('count');
  
        for ($i = 0; $i < $numberOfUsers; $i++) { 
            User::factory()->create();
        }  
        return Command::SUCCESS;
    }
}
?>

The handle() function holds the logic to insert the records in the database.

Let’s run our custom command to create 3 users

php artisan create:users 3

You can also view list of commands with following command.

php artisan list