How to check if a record is new in Laravel?

后端 未结 5 1876
星月不相逢
星月不相逢 2020-12-30 19:11

I recently started using Eloquent.

When I used PHP Active Record, there was a nice function that checked if a record was loaded from the database or is a new instan

5条回答
  •  感情败类
    2020-12-30 19:27

    We can use $appends on model if you will use it many times.. for example to check if the newly created comment is edited after created.

    class Comment extends Model
    {
         protected $appends = ['is_edited'];
    
         public function getIsEditedAttribute()
         {
              return $this->attributes['is_edited'] = ($this->created_at != $this->updated_at) ? true : false;
         }
    }
    

    You can use it like

    $comment = Comment::findOrFail(1);
    
    if($comment->is_edited){
          // write your logic here
    }
    

提交回复
热议问题