Touch Related Model Timestamps Automatically

📖 1 minute read

When you have related models in your Laravel app and need their timestamps to stay in sync, manually updating them can be tedious and error-prone.

Say you have a User model with a related Profile model. When a user updates their email, you want the profile’s updated_at to reflect that change for cache invalidation or change tracking.

Instead of manually touching the profile every time:

// Manual approach (tedious)
$user->update(['email' => '[email protected]']);
$user->profile->touch(); // Have to remember this everywhere

Use Eloquent’s $touches property to do it automatically:

class User extends Model
{
    protected $touches = ['profile'];
    
    public function profile()
    {
        return $this->hasOne(Profile::class);
    }
}

// Now updates automatically touch the related model
$user->update(['email' => '[email protected]']);
// Profile.updated_at is automatically updated!

The $touches property accepts an array of relationship method names. Eloquent will automatically call touch() on those relationships whenever the parent model is saved or updated.

Perfect for:

  • APIs that use updated_at for change tracking
  • Cache invalidation based on timestamps
  • Audit trails that need accurate modification times
  • Keeping related models in sync without manual intervention

Works with any relationship type: hasOne, hasMany, belongsTo, belongsToMany. Just name the relationship method, and Eloquent handles the rest.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *