Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

developer1237's avatar

Writing custom blueprints for migration in my large project.

I have a large project, in which I want to add some fields on all the rest of tables.

Is there any best possible way to create, so we can apply to all my tables?

0 likes
5 replies
harshshah8996's avatar

I faced the same problem and I solved it by making a new CustomBlueprint class. I wrote a separate blog on this. Just go there and you find your answers. Here I just give an example of migration file which have commonFields() method to add common fields in a model

   $schema = DB::connection()->getSchemaBuilder();

   $schema->blueprintResolver(function ($table, $callback) {
       return new CustomBlueprint($table, $callback);
   });

   $schema->create('roles', function (CustomBlueprint $table) {
       $table->bigIncrements('id');
       $table->string('name')->unique();
       $table->commonFields();
   }); 

I created CustomBlueprint class which have that method.

namespace App\common;
use Illuminate\Database\Schema\Blueprint;
class CustomBlueprint extends Blueprint
{
    public function commonFields()
    {
        $this->timestamp('created_at')->nullable();;
        $this->unsignedBigInteger('created_by')->nullable();
        $this->timestamp('updated_at')->nullable();;
        $this->unsignedBigInteger('updated_by')->nullable();
        $this->timestamp('deleted_at')->nullable();;
        $this->unsignedBigInteger('deleted_by')->nullable();
        $this->boolean('is_deleted')->default(0);
    }
}

link : https://medium.com/@harshshah8996/custom-blueprint-in-laravel-model-a772997c2fa3

2 likes
rawilk's avatar
rawilk
Best Answer
Level 47

@harsh8996 There's a much easier way to do that. Blueprint is macroable, so you can just define a macro on it in a service provider.

public function boot()
{
    Blueprint::macro('commonFields', function () {
        $this->timestamp('created_at')->nullable();
        $this->unsignedBigInteger('created_by')->nullable();
        ...
    });
}

IMO that's much easier and cleaner than creating a custom class and resolving it like you did above.

12 likes
sirony25's avatar

I faced the save problem and I solved it by making a trait and use the trait I in migration and call the function.

<?php
trait HasMigration
{
    public function commonFields(Blueprint $table): void
    {
        $table->integer('created_by')->comment('Reference id of user who created the record');
        $table->integer('modified_by')->nullable()->comment('Reference id of user who modify the record');
    }
}

Please or to participate in this conversation.