Some Useful Timestamp Tricks of Laravel

Published on August 14, 2020 1 min read

Hello artisan, today I’m going to share som timestamp tricks in Laravel. Let’s have a look:

Table of Contents

  1. Change Column Name
  2. Change Date/Time Format
  3. Order by Latest and Oldest
  4. Update Without Updating updated_at Column
  5. Update updated_at Column Only
  6. Carbon Supported
  7. Disable Timestamp

Change Column Name

If our database contains different columns instead of created_at & updated_at, we can define the names as timestamp in the model.

class User extends Model
{
    const CREATED_AT = 'created_datetime';
    const UPDATED_AT = 'updated_datetime'; 

    // other properties and methods
}

Change Date/Time Format

By default, timestamps are formatted as 'Y-m-d H:i:s'. If you need to customize the timestamp format, set the $dateFormat property on your model. This property determines how date attributes are stored in the database:

class User extends Model
{
    protected $dateFormat = 'U';

    // other properties and methods
}

Order by Latest and Oldest

We can order data by timestamp using two shortcut methods. These are latest() and oldest() methods.

// latest
User::latest()->get();

// oldes
User::oldest()->get();

Update Without Updating updated_at Column

Normally, the update eloquent method automatically updates current timestamps. We can easily stop updating timestamps during updating data like this:

$user = User::find(1);
$user->email = "[email protected]";
$user->timestamps = false;
$user->save();

Update updated_at Column Only

This trick is the opposite of previous trick. We can set new value to only updated_at column.

$user = User::find(1);
$user->touch();

Carbon Supported

Without converting to Carbon instance, we can directly perform Carbon operations on timestamps. Have a look at this example:

# example 1
$user->created_at->addDays(7);

# example 2
$user->updated_at->diffForHumans()

Disable Timestamp

Suppose, we have a table that doesn’t contain created_at & updated_at columns. In this situation, if we run eloquent query, Laravel shows error. To solve, we have just disable timestamps for the model.

class User extends Model
{
    public $timestamps = false;

    // other properties and methods
}
That’s it. Thanks for reading. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *