Today I dealt with implementing Laravel's hasMany relation in a pivot model. In my example several vehicles are assigned to a mission through a n:m relationship. Since it's necessary to protocol the vehicles' status, the pivot table hasMany logs.
To attach a relationship it's necessary to implement a pivot model. Take a look here for further information: How to define custom pivot models in Laravel
Our pivot model should look like:
class MissionVehicle extends Pivot
{
public function logs() {
return $this->hasMany(Log::class, 'mission_vehicle_id');
}
}
Since Laravel only attaches the created_at and updated_at attributes automaticallt, it's necessary to attach the id in withPivot method:
public function vehicles() {
return $this->belongsToMany(Vehicle::class)
->withPivot(['id']) // important!
->using(MissionVehicle::class);
}
Now your relationship should work.
