简体   繁体   中英

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

在此处输入图像描述

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在此处输入图像描述

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

在此处输入图像描述

Dump codes

  $userName = Auth::user();

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

    dump($request->all());

    dd('stop');

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM