onlinecode

Force update updated_at column using Eloquent Touch method

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

  1. $article= Article::find(1);
  2. $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.

  1. <?php
  2. namespace App;
  3. use IlluminateDatabaseEloquentModel;
  4. class Comment extends Model {
  5.     protected $touches=['article'];
  6.     
  7.     public functionarticle()
  8. {
  9. return$this->belongsTo('AppArticle');
  10. }
  11. }
<?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.

  1. $comment=new Comment;
  2. $comment->article_id=1;
  3. $comment->text='Text Comment';
  4. $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.

Laravel provides awesome method to save developer’s time.

Label :

PHP

Laravel PHP Framework

How To

MVC

Web Development

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

For More Info See :: laravel And github

Exit mobile version