Search code examples
laraveleloquentmany-to-many

Laravel updateExistingPivot Keeps Returning false


I have the following with many to many relationship and pivot table. So I would like to update the user_id to 1 pivot table where trophy_id = 3 . However it keeps returning 0 or false.

Trophy.php

public function users()
{
    return $this->belongsToMany('App\User', 'trophies_users', 'trophy_id', 'user_id');
}

User.php

public function trophies()
{
    return $this->belongsToMany('App\Trophy', 'trophies_users', 'user_id', 'trophy_id');
}

Pivot Table

public function up()
{
    Schema::create('trophies_users', function (Blueprint $table) {
        $table->id();
        $table->integer('trophy_id');
        $table->integer('user_id');
        $table->timestamps();
    });
}

In My controller , I am trying to update the pivot's table

UserController@index

    public function index(Request $request)
    {

        $user = User::find(1);
        $trophyId = 3;
        $attributes = ['user_id' => 1];
        $res = $user->trophies()->updateExistingPivot($trophyId , $attributes);
        dd($res); //Keeps returning 0 or false
    }

Solution

  • You are passing attribute to updateExistingPivot which is for updating extra attribute on a pivot table.

    For example, assume we want to store a color for each companion of user and trophy, we can achieve that by adding an extra column in pivot table and saving color data on it as below:

    |---------------------|
    |       column        |
    |---------------------|
    |        id           |
    |---------------------|
    |       user_id       |
    |---------------------|
    |      trophy_id      |
    |---------------------|
    |        color        |
    |---------------------|
    

    If you want to update a relationship on pivot table, use sync method.

    $user=User::find(1);
    $trophies_id=[1, 2, 3];
    $user->trophies()->sync($trophies_id);