n Tricks with Timestamps in Laravel 7 | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

Disable Timestamps

If your DB table doesn't contain timestamp fields created_at and updated_at, you can specify that Eloquent model wouldn't use them, with $timestamps = false property.

class Company extends Model {

    public $timestamps = false;



Change Timestamp Column Names

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time'; 


Change Timestamp Date/Time Format

     * The storage format of the model's date columns.
     * @var string
    protected $dateFormat = 'U';


Order by Timestamp with latest() and oldest()

Instead of:

User::orderBy('created_at', 'desc')->get();

You can do it quicker:



Instead of:

User::orderBy('created_at', 'asc')->get();

You can do it quicker:



Update without touching updated_at

$user = User::find(1);
$user->profile_views_count = 123;
$user->timestamps = false;


Set new value to ONLY updated_at column

So, instead of:

$user->update(['updated_at' => now()]);

You can use a shorter method:



Timestamp Fields are Carbon Automatically

By default, both created_at and updated_at are casts as $dates of Eloquent model, so you can perform Carbon operations on them, without converting to Carbon instance.






Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts


Page Facebook