Force update updated_at column using Eloquent Touch method
In this post we will give you information about Force update updated_at column using Eloquent Touch method. Hear we will give you detail about Force update updated_at column using Eloquent Touch methodAnd how to use it also give you demo for it if it is necessary.
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
- $article= Article::find(1);
- $article->touch();
$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 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.
- <?php
- namespace App;
- use IlluminateDatabaseEloquentModel;
- class Comment extends Model {
- protected $touches=['article'];
- public functionarticle()
- {
- return$this->belongsTo('AppArticle');
- }
- }
<?php namespace App; use IlluminateDatabaseEloquentModel; class Comment extends Model { protected $touches = ['article']; public function article() { return $this->belongsTo('AppArticle'); } }
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();
$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.
Hope this code and post will helped you for implement Force update updated_at column using Eloquent Touch method. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs