I think creating Intermediate model does better job otherwise we will have to add primary uuid whenever we create new record.
use Webpatser\Uuid\Uuid;
use Illuminate\Database\Eloquent\Relations\Pivot;
class ProjectAssignee extends Pivot
{
public $incrementing = false;
protected $keyType = 'string';
protected $primaryKey = 'id';
protected $guarded = [];
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->id = (string) Uuid::generate(4);
});
}
}
Now we can create attach easily
Project::first()->assignees()->attach(Assignee::inRandomOrder()->take(5)->pluck('id')->toArray());
Don't forget to chain using
method to tell relationship about intermediate table.
public function assignees(){return $this->belongsToMany(
Assignee::class,
'projects_assignees',
'project_id',
'assignee_id')
->using(ProjectAssignee::class);}