Force update updated_at column using Eloquent Touch method

Force update updated_at column using Eloquent Touch method

In this Laravel tutorial, I will tell you how to update updated_at column without touching any fields in Laravel using touch() method.

You can also update the updated_at field with related model by providing their function name to $touches property in Eloquent Model.

You can update the updated_at column with current timestamp whenever user logs in into application by using touch() method.

Example 1

  1. $article = Article::find(1);
  2. $article->touch();

It will update only updated_at column with current timestamp without updating any other columns in "articles" table.

Example 2

Sometime you need to get all active articles in order that have recently updated comments so in that case whenever any comment is posted against any article you can modify the updated_at column with current timestamp in the articles table so that you can order them by updated_at field.

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Comment extends Model {
  5.     protected $touches = ['article'];
  6.     
  7.     public function article()
  8. {
  9. return $this->belongsTo('App\Article');
  10. }
  11. }

Now, whenever you will use "Comment" Model to save comments, update comments, etc. the updated_at column in articles table will update automatically.

  1. $comment=new Comment;
  2. $comment->article_id=1;
  3. $comment->text='Text Comment';
  4. $comment->save();

This is really very useful to get records from the table without checking any updates in their child tables.

Phone: (+91) 8800417876
Noida, 201301