How to update a pivot table using Eloquent in laravel 5

Here is a small example of how to update the pivot table column

    $query = Classes::query();
    $query = $query->with('trainees')
                   ->where('user_id', Auth::id())
                   ->find($input['classId']);

    foreach ($query->trainees as $trainee) {
       $trainee->pivot->status = 1 //your column;
       $trainee->pivot->save();
    }

Note: make sure your relation data must in an array Hope its help you :) happy coding


You may use one of these two functions, sync() attach() and the difference in a nutshell is that Sync will get array as its first argument and sync it with pivot table (remove and add the passed keys in your array) which means if you got 3,2,1 as valued within your junction table, and passed sync with values of, 3,4,2, sync automatically will remove value 1 and add the value 4 for you. where Attach will take single ID value

The GIST: if you want to add extra values to your junction table, pass it as the second argument to sync() like so:

$message = Messages::find(123);
$user = User::find(4);

// using attach() for single message
$user->message()->attach($message->id, [
    'status' => 1
]);



$message2 = Messages::find(456); // for testing

// using sync() for multiple messages
$user->message()->sync([
    $message->id => [
        'status' => 1
    ],
    $message2->id => [
        'status' => 1
    ],
]);

The code below solved my problem:

$messages  = Message::where('message_id', $id)->get();
foreach($messages as $message)
   $message->users()->updateExistingPivot($user, array('status' => 1), false);