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();
});
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!
- 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');
});
}
- 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();
});
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!