Skip to content
Advertisement

Laravel Sync username into pivot table

I have an extra column for usernames in my role_user pivot table, how can I sync the username with the roles ?

role_user pivot table

enter image description here

I need to sync the user name in the name field

This is the update function where I have added the sync

JavaScript

Here’s the relationship in my User Model

JavaScript

Here’s the role_user table migration

JavaScript

I got this error if when I tried enter image description here

This is what i get when i dump the request and Auth user name

enter image description here

Dump codes

JavaScript

Advertisement

Answer

You need an associative array keyed by the role id with an array for each element to add things to the pivot table. Currently you just have an array of role ids, which is fine for sync as is, but not if you want to also set the extra pivot data. You need an array like:

JavaScript

You can use array_fill_keys to build this array with the keys being the role ids and the values being the array with the ‘name’ field:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement