Thursday, November 10, 2016

Laravel: Touching Parent Timestamps

Hi

Today we will learn how to use Touch property/method in Laravel Eloquent.

Sometime we need to update parent's model timestamp when the child model is updated.

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, we may want to automatically "touch" the updated_at timestamp of the owning Post. Laravel Eloquent makes it easy. We need to add a touches property containing the names of the relationships to the child model.

 <?php  
 namespace App;  
 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\Post');  
   }  
 }  

Now, when we update a Comment, the owning Post will have its updated_at column updated as well:

 $comment = App\Comment::find(1);  
 $comment->text = 'Edit to this comment!';  
 $comment->save();  

Thanks


1 comment:

  1. hey... Great work . I feel nice while i reading blog .You are doing well. Keep it up. We will also provide dial QuickBooks Technical Support
    to reach us call to 1-855-756-1077 for instant help.

    ReplyDelete