Jose Jimenez
Jose Jimenez
Software Architect & Developer
> >

Package to make Laravel 9 closure pivot tables

Published in Laravel, PHP, Database on Apr 27, 2022

Laravel 9 released with new closure migrations, all the packages I found dealt with the old way of doing migrations which is why I created the this package Laravel Make Migration Pivot.

At the time of writing 1.0.0 accepts two models. Under the hood the system will inspect the two models and generate the pivot table along with foreign key names.

Assuming I have a Blog and Category model, I would run the following command:

1php artisan make:pivot Category Blog

That will generate

 1 
2// ...
 3 
4return new class extends Migration {
5 public function up()
6 {
7 Schema::create('blog_category', function (Blueprint $table) {
8 $table->foreignIdFor(Blog::class)->constrained()->onDelete('cascade');
9 $table->foreignIdFor(Category::class)->constrained()->onDelete('cascade');
10 $table->primary(['blog_id', 'category_id']);
11 
12 $table->index('blog_id');
13 $table->index('category_id');
14 });
15 }
16 
17 // ...
18}

You are free to configure the stub that is used to generate the migration, do additional optimizations or add additional logic to the default stub.

1php artisan vendor:publish --tag="laravel-make-migration-pivot-stubs"

That will generate the stub in the following path stubs/migration.pivot.stub, the following replacements can be utilized in your stub:

When referencing the models as first or second, please keep in mind that the system will sort the models in alphabetical order.

  • {{ table }} name of the pivot table to create
  • {{ first_model_name }} name of the first model
  • {{ second_model_name }} name of the second model
  • {{ first_table_id }} Key ID of the first model
  • {{ first_table_foreign_id }} Foreign Key ID of the first model
  • {{ second_table_id }} Key ID of the second model
  • {{ second_table_foreign_id }} Foreign Key ID of the second model
  • {{ uses }} returns the models that will be used in your script, this is for the template called after <?php
  • ‌{{ first_model_path }} returns the model path to your first model.
  • ‌{{ second_model_path }} returns the model path to your second model.

There are additional features I would like to add to the package which I will develop over time.