1-Create a migration for the pivot table by running the following command in your terminal:
php artisan make:migration create_table_name_table
2- In the migration file, create the pivot table with the columns that you need for your relationship.
<?php Schema::create('table_name', function (Blueprint $table) { $table->unsignedBigInteger('model1_id'); $table->unsignedBigInteger('model2_id'); // add any other columns that you need for your relationship $table->timestamps(); // set up composite key $table->primary(['model1_id', 'model2_id']); // set up foreign keys $table->foreign('model1_id')->references('id')->on('model1_table')->onDelete('cascade'); $table->foreign('model2_id')->references('id')->on('model2_table')->onDelete('cascade'); });
3- In your models, set up the relationship between the two models and the pivot table.
<?php class Model1 extends Model { public function model2s() { return $this->belongsToMany(Model2::class, 'table_name', 'model1_id', 'model2_id'); } } class Model2 extends Model { public function model1s() { return $this->belongsToMany(Model1::class, 'table_name', 'model2_id', 'model1_id'); } }
4- To display the data in a pivot table format in your application, you can use the withPivot()
method to retrieve the additional columns from the pivot table.
<?php $model1 = Model1::find(1); foreach ($model1->model2s as $model2) { echo $model2->pivot->column_name; // include any other columns that you need from the pivot table }