Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To create a custom pivot table for a one-to-many relationship using polymorphic function in Laravel, follow these steps:

  1. Create a migration file for the pivot table:
php artisan make:migration create_pivot_table_name_table --create=pivot_table_name
  1. In the migration file, add the columns for the foreign keys and any additional data that is needed for the relationship:
public function up()
{
    Schema::create('pivot_table_name', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('user_id');
        $table->unsignedBigInteger('pivotable_id');
        $table->string('pivotable_type');
        $table->timestamps();
    });
}
  1. In the relevant models, define the morphMany and morphToMany relationships:
class User extends Model
{
    public function pivotables()
    {
        return $this->morphToMany('App\Pivotable', 'pivotable');
    }
}

class Pivotable extends Model
{
    public function users()
    {
        return $this->morphedByMany('App\User', 'pivotable');
    }
}
  1. Use the custom pivot table in the relationship method:
$user->pivotables()->attach($pivotableId, ['extra_data' => 'value']);

or

$pivotable->users()->attach($userId, ['extra_data' => 'value']);

Note: Remember to replace 'pivottablename' and 'Pivotable' with your own table and model names. Also, make sure to update the column names to match your own foreign keys.