Ask Your Question
3

How can I create a custom pivot table for a one-to-many relationship using polymorphic function in Laravel?

asked 2022-04-22 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-09-08 22:00:00 +0000

nofretete gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-22 11:00:00 +0000

Seen: 8 times

Last updated: Sep 08 '21