Laravel eloquent model increment with or without updating timestamps

Panjeh
3 min readFeb 28, 2019

--

Problem:
You may need to increment a field in a record of a table (a single attribute of a Laravel Model) and do not want update the updated_at timestamps.

Suppose the field is popularity when you do this:

Plan::find($planId)->increment('popularity');

Besides incrementing popularity, this will update the timestamps of that record too!

While you don’t want it.

Before you continue with the rest of this tutorial, I would like to introduce two packages for Laravel that I have recently developed: Laravel Pay Pocket, a modern multi-wallet package, and Laravel Failed Jobs, a UI for the Laravel Failed Jobs Table. I hope they may be of help to you.

https://github.com/HPWebdeveloper/laravel-pay-pocket
https://github.com/HPWebdeveloper/laravel-failed-jobs

Solution-1:

$plan=Plan::find($planId);$plan->timestamps = false;
$plan->increment('popularity');
$plan->save();

As an example see how laravel does the same when update the remember_me token at each logout without touching the timestamps.

In class EloquentUserProvider in Illuminate\Auth directory (this link) in the updateRememberToken() method Laravel first assigns the value (true or false) of timestamps to a temporary variable and after saving the remember_token in the $user model retrieves its original value.

Solution-2:

Using a simple query builder which does not update timestamps on its own:

timestamps (updated_at) is not touched:

DB::table(‘plans’)
->where(‘id’, $planId)
->increment(‘popularity’,1);

timestamps (updated_at) is touched:

DB::table(‘plans’)
->where(‘id’, $planId)
->increment(‘popularity’,1,[‘updated_at’ => Carbon::now()]);

Solution-3:

By default, Eloquent expects created_at and updated_at columns to exist on your tables. If you do not wish to have these columns automatically managed by Eloquent, set the $timestamps property on your model to false:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Plan extends Model
{
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
}

In this case, whenever you want the timestamps to be updated, you need to manually assign them value like

$plan->updated_at = Carbon::now();

Thank you for reading! If you enjoyed this article:

Clap it ! Share it! Follow Me in Medium!

Also I’d like to hear your opinion on this article. If you have any doubt, question or suggestion please leave a comment below.

Have a very wonderful day!

Previous Stories You will Love:

--

--

Panjeh
Panjeh

Written by Panjeh

Posting about Python and Laravel

No responses yet