Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

Touch parent updated_at easily in Laravel


When a model belongsTo or belongsToMany another model, such as a Comment which belongs to a Post, it is sometimes helpful to update the parent's timestamp when the child model is updated. For example, when a Comment model is updated, you may want to automatically "touch" the updated_at timestamp of the owning Post. Eloquent makes it easy. Just add a touches property containing the names of the relationships to the child model:


namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
     * All of the relationships to be touched.
     * @var array
    protected $touches = ['post'];

     * Get the post that the comment belongs to.
    public function post()
        return $this->belongsTo('App\Models\Post');


Now, when you update a Comment, the owning Post will have its updated_at column updated as well, making it more convenient to know when to invalidate a cache of the Post model:

$comment = App\Models\Comment::find(1);

$comment->text = 'Edit to this comment!';



Add new comment

Restricted HTML


Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.


Contact Us

All the content is FREE but I still need your help


Become a patreon