Laravel 10 Create Custom Artisan Command Example

By Hardik Savani November 5, 2023 Category : Laravel

Hi,

Now, let's see a tutorial of laravel 10 create custom artisan command. Here you will learn laravel 10 create custom artisan. We will look at an example of laravel 10 custom artisan command. I’m going to show you how to create custom artisan command in laravel 10 create artisan command laravel 10.

Laravel provides its own artisan commands for creating migration, model, controller, etc. but if you want to create your own artisan command for project setup, admins users, etc. then I will help you how to create a custom artisan command in laravel application.

In this example, we will create a custom "php artisan create:users" command using laravel artisan command. The command will take one argument in an integer. Then we will create users using a factory based on the command argument.

so let's follow the below step to create your own artisan command in laravel app.

Step 1: Install Laravel

first of all, we need to get a fresh Laravel version application using the bellow command, So open your terminal OR command prompt and run the bellow command:

composer create-project laravel/laravel example-app

Step 2: Database Configuration

In this step, we need to add database configuration in .env file. so let's add following details and then run migration command:

.env

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=laravel9_blog

DB_USERNAME=root

DB_PASSWORD=password

Next, run migration command to create users table.

php artisan migrate

Step 3: Generate Artisan Command

In this step, we need to create "CreateUsers" class using following command. Then copy below code into it. we will add "create-users" command name.

php artisan make:command CreateUsers

Then let's update following command file.

app/Console/Commands/CreateUsers.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

use App\Models\User;

class CreateUsers extends Command

{

/**

* The name and signature of the console command.

*

* @var string

*/

protected $signature = 'create:users {count}';

/**

* The console command description.

*

* @var string

*/

protected $description = 'Create Dummy Users for your App';

/**

* Execute the console command.

*/

public function handle(): void

{

$numberOfUsers = $this->argument('count');

for ($i = 0; $i < $numberOfUsers; $i++) {

User::factory()->create();

}

}

}

Step 4: Use Created Artisan Command

In this step, we will run our custom command and check artisan command using "php artisan list" command.

So, let's run following custom command to create multiple users:

php artisan create:users 10

php 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

Output:

I hope it can help you...

Shares