you will learn how to create a custom artisan command in the Laravel 8 application and use the custom laravel artisan command to generate the test data or user records and insert them into the database
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
php artisan make:command generateUserData
you have to go to the app/Console/Commands/generateUserData.php
The handle() function holds the logic to run the factory tinker command, manifesting the records in the database
<?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
php artisan create:generate-users 250
Finally I invite you to try the next Artisan in the next link in the handle() function and enjoy the results
https://laravel.com/docs/8.x/artisan#writing-output
https://laravel.com/docs/8.x/artisan#tables
https://laravel.com/docs/8.x/artisan#progress-bars
I hope you enjoyed the code.
Top comments (0)