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

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');

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:

[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]);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement