skip to Main Content

I want to increment the calls / views for a blog. In the controller I have the following two lines:

$post->views = $post->views + 1;
$post->save();

I wonder if the update method might be faster?

Another question about incrementing. Is there a Laravel function that can be used to increment?

2

Answers


  1. In my opinion, both writing methods should be equally fast. Here is your second question. You can use increment()function.

    // 1.
    Post::where('id', $id)->increment('views');
    // 2.
    Post::find($id)->increment('views'); 
    // 3.
    $post->views++;
    $post->save();
    
    Login or Signup to reply.
  2. Both methods will be broadly the same, update() also calls save().

    From the EloquentModel API:

    public function update(array $attributes = [], array $options = [])
    {
        if (! $this->exists) {
            return false;
        }
        return $this->fill($attributes)->save($options);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search