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:

php artisan make:pivot Category Blog

That will generate

// ...

return new class extends Migration {
    public function up()
        Schema::create('blog_category', function (Blueprint $table) {
            $table->primary(['blog_id', 'category_id']);

    // ...

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.

php 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.