Hello today we are going to talk about how to create custom command Artisan to perform a specific task. Actually, there are built-in Artisan command in Laravel application, example if we want to start Laravel server then we will type command "php artisan serve". But for today I will show you how do we create own command to generate specific dummy users data with our own command artisan base on value input.
This step you will install Laravel with composer, so let's try command below to download fresh Laravel
composer create-project laravel/laravel LaravelApp
cd LaravelApp
Now we are going to configure database connection, so in Laravel root directory you will see a file named .env. and find the below keys and modified following credential
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password
This step we are going to create a file command, so execute following command to generate a file and we are going to implement in next step.
php artisan make:command createUsers
The command will create a new file, so open that file and modified as below code
Open file app -> Console -> Commands -> createUsers.php
<?php
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Command;
class createUsers extends Command
{
protected $signature = 'create:users {value}';
protected $description = 'Command description show in help';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$usersNum = $this->argument('value');
for ($i = 0; $i < $usersNum ; $i++)
{
User::factory()->create();
}
}
}
We are going to test the command if it work so we will create 20 new dummy users data in database by following command:
php artisan create:users 20
In database you will see in table user will contain 20 sample records of users
Thank you for come and read today. Please have a nice day!!
You might Also Like:
Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him