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.
- $article = Article::find(1);
- $article->touch();
It will update only updated_at column with current timestamp without updating any other columns in "articles" table.
Example 2Sometime 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.
- <?php
- namespace App;
- use Illuminate\Database\Eloquent\Model;
- class Comment extends Model {
- protected $touches = ['article'];
- public function article()
- {
- return $this->belongsTo('App\Article');
- }
- }
Now, whenever you will use "Comment" Model to save comments, update comments, etc. the updated_at column in articles table will update automatically.
- $comment=new Comment;
- $comment->article_id=1;
- $comment->text='Text Comment';
- $comment->save();
This is really very useful to get records from the table without checking any updates in their child tables.