Search code examples
laravelpivoteloquentuuid

Laravel Pivot table id column


In Laravel and Eloquent you can use ManyToMany-Relations with a pivot table. The problem in my case is the automatic ID of the pivot row. Can I change how the ID is generated? I want to use UUIDs for that matter.

For other Objects you can just implement this behaviour in the Model, but there is no model for pivot objects.

Did I miss something?


Solution

  • Yeah, wherever you are adding new records to the pivot table, either through attach() or sync(), you give it a key/value array of additional items to put into the pivot table as the second parameter.

    So for example $user->roles()->attach($role, array('id' => $uuid));

    If you are doing this, it might be useful to also make sure your id isn't set to auto increment.

    It might also be important to note that a lot of people don't even have an id column on their pivot table because it's usually not required unless you plan on creating a model for it, or it contains some other foreign key for some reason besides the 2 it would usually have.