How to update timestamp in pivot table in Laravel

Last updated at April 17, 2021


When insert a new row to pivot table, we can use attach() method like this:

$company = Company::find(1);

But this will not update created_at and updated_at timestamps column in pivot table.

To update timestamps, use withTimestamps() method on the relationship method.

class Company extends Model
  public function users()
    return $this->belongsToMany(User::class)->withTimestamps();