Laravel Model Timestamps-Tips and Tricks

Sharing is caring!

329 Views -

Timestamps

In Laravel, Eloquent(Model) expects created_at and updated_at columns exist on your tables.
The created_at and updated_at timestamps will automatically be set when the save method is used, so there is no need to set them manually. There are multiple things you can do, let’s try.

1-Disable Timestamps

If you do not want to have these columns automatically managed by your Eloquent, set the $timestamps property on your model to false.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    
    public $timestamps = false;
}

 

2-Use different column names for Timestamp
If you want to use different names of the columns used for timestamps, you need to set the CREATED_AT and UPDATED_AT constants in your model.

<?php

class User extends Model
{
    const CREATED_AT = 'create_date';
    const UPDATED_AT = 'update_date';
}

 

3-Customize Timestamp Format
If you want to modify the format of your timestamps, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

 4-Order by latest / oldest
The latest and oldest methods allow you to easily order results by date. By default, the result will be ordered by the created_at column. Or, you can pass the column name that you want to sort by.

$user = DB::table('users')
                ->latest()
                ->first();
$user = DB::table('users')
                 ->orderBy('created_at', 'desc')
                 ->get();

 

 

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments