1
votes

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

public function update(Request $request, User $user)
    {
       
        $role = $request->role;

        $userName = Auth::user();

        $user->roles()->sync([$role=>['name'=>$userName->name]]);

        dd('stop'); 
   }

Here's the relationship in my User Model

 public function roles()
{
    return $this->belongsToMany(Role::class)->withPivot(['name'])->withTimestamps();
}

Here's the role_user table migration

 class CreateRoleUserTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('role_id');
            $table->unsignedBigInteger('user_id');
            $table->string('name')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('role_user');
    }
}

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

  $userName = Auth::user();

    dump('Auth user name  = '.$userName->name);

    dump($request->all());

    dd('stop');
2
wouldn't you want $user->name instead of $userName->name ... since $user is the user for that id you are adding to the pivot table? - lagbox
can you print what are you sending in request? are we sure you are logged in and auth()->user() doesn't return null? and make sure $request->role is id of role or it won't work. - Mojtaba Hn
@lagbox well variable naming has some problems here, since $userName represents User object, $userName->name makes sense. - Mojtaba Hn
well we don't know how your Auth is setup ... but the authenticated user is not the same as the user you are syncing the role for potentially, why do you want the current authenticated user's name for someone else's user id? - lagbox
@lagbox I have updated the question, I need the Auth user name to be added to the pivot table. - Jareer

2 Answers

3
votes

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:

[1 => ['name' => ...], 2 => ['name' => ...]]

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:

$roles = (array) $request->input('role', []);

$forSync = array_fill_keys($roles, ['name' => $userName->name]);
1
votes

Ok you almost done it correct. except..

You need to write it like this ( using Collection mapWithKeys method):


$roles = collect($request->role)->mapWithKeys(function($role){
    return [$role => ['name' => Auth::user()->name];
})->toArray();

$user->roles()->sync($roles);

the reason for this is that you need to specify pivot table parameters for each role separately. so instead of [[1,2] => ['name' => 'John']] you need to have [1 => ['name' => 'John'],2 => ['name' => 'John']] for it to work.