Using Macros to Simplify Migrations
How to add helper methods to the Blueprint Facade.
March 7, 2023
1k ViewsShort Answer
Using the Blueprint facade, create a macro and register it in a service provider.
Implementing a Slug Helper
If you've made a website, you might have used a slug to make your URLs look neat. But doing it over and over can get annoying. You can simplify things by creating helper methods to add or remove a slug column.
To do this we can add a macro to the boot method of a registered service provider, such as AppServiceProvider.php
.
namespace App\Providers;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\ColumnDefinition;
use Illuminate\Support\Fluent;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
Blueprint::macro('slug', function (?int $length = null): ColumnDefinition {
return $this->char('slug', $length);
});
Blueprint::macro('dropSlug', function (): Fluent {
return $this->dropColumn('slug');
});
}
}
Usage
In a migration you can call $table->slug()
and $table->dropSlug()
.
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void
{
Schema::table('posts', static function (Blueprint $table) {
$table->slug();
});
}
public function down(): void
{
Schema::table('posts', function (Blueprint $table) {
$table->dropSlug();
});
}
};
Want to see an example of how a simple trick will take this example to the next level and supercharge your queries?
Subscribe to get immediate access to this trick as well as all the exclusive content on this site.