Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To utilize Laravel's MorphPivot when dealing with polymorphic relationships on both sides, follow these steps:

  1. Define the morphTo relationship on both models (e.g., User and Event).

  2. Define the morphToMany relationship on the pivot model (e.g., EventUser).

  3. Extend the MorphPivot class and customize it according to your needs. This custom class will represent the pivot table and allow you to access additional data related to the pivot.

  4. Update the relationship methods on both models (e.g., User and Event) to use the custom pivot class.

Here is some example code to illustrate the process:

class User extends Model
{
    public function events()
    {
        return $this->morphToMany(Event::class, 'eventable', 'event_user')
                    ->using(EventUser::class)
                    ->withPivot(['attended']);
    }

    public function notifications()
    {
        return $this->morphMany(Notification::class, 'notifiable');
    }
}

class Event extends Model
{
    public function users()
    {
        return $this->morphToMany(User::class, 'userable', 'event_user')
                    ->using(EventUser::class)
                    ->withPivot(['attended']);
    }
}

class EventUser extends MorphPivot
{
    protected $table = 'event_user';

    protected $fillable = ['attended'];

    public function notification()
    {
        return $this->morphOne(Notification::class, 'notifiable');
    }
}

In this example, the pivot table is called event_user, and we're using the EventUser class to represent it. We've also added a notification() method to the EventUser class, which will allow us to access the notification related to the pivot.

By using MorphPivot and custom pivot classes, we can add additional functionality and data to the pivot table, making it a more powerful tool in our application's architecture.