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:
As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him