Simplify Laravel Migrations with Macros

Cak Suku - Mar 4 - - Dev Community

Have you ever found yourself repeatedly writing the same fields in your Laravel migrations?

It can be tedious, right? But guess what, there’s a much easier way to handle this! Introducing Laravel Blueprint Macros.

Blueprint Macros allow you to extend Laravel’s migration schema functionality and add custom logic as needed. This way, you can avoid repeating the same fields in your migrations and increase your productivity.

Let me show you how.

Before Using Blueprint Macros

You might have this repetitive code in your migrations :

Schema::create('candidates', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->string('phone_number');
    $table->string('email');
    $table->string('fax');
    $table->timestamps();
});

Schema::create('employees', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->string('rank');
    $table->string('occupancy');
    $table->timestamps();
});

Enter fullscreen mode Exit fullscreen mode

As you can see, the fiels name, email and password is repeated in that two tables. Now imagine doing this for every migration file in your project. Tedious, right?

After Using Blueprint Macros

Now, let’s use Blueprint Macros to simplify things!

  1. First, define a macro in your AppServiceProvider.php or any service provider:
use Illuminate\Database\Schema\Blueprint;

....

public function boot()
{
    Blueprint::macro('accountFields', function () {
        $this->string('name');
        $this->string('email')->unique();
        $this->string('password');
    });
}
Enter fullscreen mode Exit fullscreen mode
  1. Then, apply it in your migrations like this :
Schema::create('candidates', function (Blueprint $table) {
    $table->id();
    $table->accountFields();
    $table->string('phone_number');
    $table->string('email');
    $table->string('fax');
    $table->timestamps();
});

Schema::create('employees', function (Blueprint $table) {
    $table->id();
    $table->accountFields();
    $table->string('rank');
    $table->string('occupancy');
    $table->timestamps();
});
Enter fullscreen mode Exit fullscreen mode

By defining the accountFields macro, you avoid repeating the same column definitions across multiple migration files. It’s clean, efficient, and easy to manage.

Why Use Blueprint Macros? :

  • Reusable: Write once, use everywhere.
  • DRY Principle: Avoid repeating yourself.
  • Clean Code: Keep your migration files neat and easy to read.

If you found this tip helpful, don’t forget to share it with others who might benefit from it!

.