About Us Blog Contact Us Request a quote

Laravel 12 create custom artisan command

Install Laravel 12 App

Run below this command


composer create-project laravel/laravel example-app

Setup mysql database

update .env file


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel12app //database name
DB_USERNAME=root
DB_PASSWORD=

create command

Run below this command


php artisan make:command CreateContact

app\Console\Commands\CreateContact.php like as below code


<?php

namespace App\Console\Commands;

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

class CreateContact extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'create:contact {count}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create Dummy contacts for your App';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $numberOfContact = $this->argument('count');  

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

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

        }   

        return 0;
    }
}

Create Model & Migration


php artsan make:model Contact -m

app\Models\Contact.php like as below code


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Contact extends Model
{
    use HasFactory;
    protected $fillable = [
        'name',
        'email',
        'phone',
        'address',
    ];

}

database\migrations\2025_02_27_075816_create_contacts_table.php like as below code


<?phpp

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('phone')->unique();
            $table->text('address');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('contacts');
    }
};

Run below this command


php artisan migrate

Run Laravel App:

Now Run your laravel 12 app after run these below commands


php artisan create:contact 5

Go to your database table records



Recent Posts