disable or enable timestamp in laravel project

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 date and time of day, sometimes accurate to a small fraction of a second.

Real life example for timestamps are below :

  • To store information like when data is created, updated, 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 post is created or when someone shared of liked 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.

  • Enable or Disable Timestamps Record Wise
  • Enable or Disable Timestamps Model Wise

Enable or Disable Timestamps Record Wise

We can disable or enable timestamps for particular record using it in 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.

Example :

    
        //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 model by just adding public $timestamps = false; for disabling timestamp and public $timestamps = false; for enabling timestamps into Model.
let's take an example for it.

Example :

    
<?php

namespace App;
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 is true.

Conclusion

In this example, we demonstrated what is timestamps, where we can use it and how to use timestamp into Laravel application specifically with record wise or model wise. we suggest you to enable timestamps for your application so you can keep record for changes and analysis data based on timestamp.


Share your thoughts

Ask anything about this examples