Enable Disable timestemp in laravel

Before starting let's understand what is timestamps.

What is Timestamps?

A timestamp is a sequence of characters or encoded information identifying when a certain event occurred, usually giving a date and time of day, sometimes accurate to a small fraction of a second.

Real-life examples for timestamps is below :

  • To store information like when data is created, updated, or deleted.
  • In games, showing how long the player has spent in the game so far.
  • Files may contain a timestamp that shows when the file was last changed or updated.
  • In social media, when a post is created or when someone shared of a liked a post.

Timestamps allows you to automatically record the time of certain events against your entities. This can be used to provide similar behavior to the timestamps feature in Laravel's Eloquent ORM.
But sometimes we need to disable or enable timestamps to Laravel models.
We can do that by two methods.

  1. Enable or Disable Timestamps Record Wise
  2. Enable or Disable Timestamps Model Wise

Enable or Disable Timestamps Record Wise

We can disable or enable timestamps for the particular records using them in a particular controller. we just have to add $model_name->timestamps = false; for disabling timestamp and $model_name->timestamps = true; for enabling timestamps into our controller file.
let's take an example for it.

//we add simple example to add user into user model
$user = new \App\Models\User();
$user->name ="Xyz";
$user->email = "xyz@xyz.com";
$user->password = Hash::make('12345678');
$user->timestamps = false;
//replace false with true to enable timestamps.
$user->save();

Using this method we can enable or disable timestamps for particular database record it will pass null value to database.

Enable or Disable Timestamps Model Wise

We can also disable or enable timestamps for the model by just adding public $timestamps = false; for disabling timestamps and public $timestamps = false; for enabling timestamps into the Model.
let's take an example for it.


namespace App\Models;

use Illuminate\Database\Eloquent\Model;
class Users extends Model
{
    public $fillable = ['title'];
    public $timestamps = false;
    //remove this line to re-enable timestamps
}

By Default timestamps are true.

Conclusion

In this example, we demonstrated what are timestamps, where we can use it, and how to use timestamps in Laravel applications specifically record-wise or model-wise. we suggest you enable timestamps for your application so you can keep a record of changes and analyze data based on timestamps.