To create a custom pivot table for a one-to-many relationship using polymorphic function in Laravel, follow these steps:
php artisan make:migration create_pivot_table_name_table --create=pivot_table_name
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();
});
}
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');
}
}
$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.
Asked: 2022-04-22 11:00:00 +0000
Seen: 8 times
Last updated: Sep 08 '21