Create a custom artisan command example; Through this tutorial, you will learn how to create and use a custom artisan command in laravel 10/9 apps.
Laravel 10/9 Create Custom Artisan Command Example
Use the following steps to create and use custom artisan command in laravel 10/9 apps:
- Step 1: Download New Laravel App
- Step 2: Connect Laravel App to Database
- Step 3: Create Artisan Command
- Step 4: Update Code in Artisan Command
- Step 5: Run Artisan Command
Step 1: Download New Laravel App
First of all, open terminal and execute the following command on command line to install or download new laravel 9 apps:
composer create-project laravel/laravel --prefer-dist laravel-demo
Step 2: Connect Laravel App to Database
Then connect laravel app to database; so visit laravel app root directory and find .env file. And add the database details; as follows:
DB_CONNECTION=mysql DB_HOST=localhost DB_PORT=3306 DB_DATABASE=laravel_db DB_USERNAME=root DB_PASSWORD=
Now execute the following command on command line to migrate Artisan command:
php artisan migrate
Step 3: Create Artisan Command
Using the make:command Artisan command, we can create or generate artisan command, so execute the following command on command line to create a new command:
php artisan make:command generateUserData
Step 4: Update Code in Artisan Command
Then visit app/Console/Commands/ directory and open generateUserData.php file. And update the following code into it:
<?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();
}
}
}
Step 5: Run Artisan Command
Finally, we have to type the custom artisan command on the console screen and execute it on command line to generate the users’ data into the database:
php artisan create:generate-users 250
Conclusion
Through this tutorial, we have learned how to create and use a custom artisan command in laravel 9 apps.