Laravel 9 Create Custom Artisan Command Example Tutorial
Create a new command using command:
php artisan make:command CreateUsers
Open app/Console/Commands/CreateUsers.
Set name and signature of your command and write a small description about your command.
Inside handle function you can write your logic. It should look something like this:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\User;class CreateUsers extends Command
{
protected $signature = 'create: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();
}
}
}
To build a new Laravel Artisan command, you have to go to the app/Console/Commands/CreateUsers.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.
Run Custom Artisan Command
In the final step, we have to type the custom artisan command on the console screen and execute it to create 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:users 10php artisan create:users 5
You can check in your users table, it will created records there.
Next, you can check your custom command on list as well.
php artisan list