How to create custom command in laravel?

In this post we will learn about how to create custom command in laravel, Whether youre a beginner or an experienced developer, this post will help you enhance your web applications and boost your productivity.


We will use our custom command to run a laravel factory, If you do not no how to use factory in laravel, then please check this post


So lets start by creating a command, To create a laravel commnad use the commnad below.

php artisan make:command PostFactory

A file should've be generated in : /app/Console/Commands/PostFactory.php

Now we will edit variable which are $signature and $description and A function which is handle, The handle function is where you write the code that should be executed when your custom command is called.

<?php

namespace App\Console\Commands;

use App\Models\Post;
use Illuminate\Console\Command;

class PostFactory extends Command
{
    public const SUCCESS = 0;
    public const FAILURE = 1;
    public const INVALID = 2;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'posts:create';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate 10 fake records for post.';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // for errors : $this->error('ERROR MESSAGE HERE');
        // for warning / invalid : Log::warning('Please create factory first');

        $this->info('Factory started running.');
        Posts::factory()->count(10)->create();
        $this->info('Successfully processed!');

        return self::SUCCESS;
    }
}