search
HomePHP FrameworkLaravel8 Tips for Using Laravel Model Timestamps

By default, the Laravel Eloquent model default data table has two fields: created_at and updated_at. Of course, we can make a lot of custom configurations and implement many interesting functions. Below are examples.

1. Disable timestamp

If the data table does not have these two fields, Model::create($arrayOfValues); when saving the data - you will see SQL error. Laravel cannot find these two fields when automatically filling created_at / updated_at.

Disable automatic filling of timestamps, just add the previous attribute to the Eloquent Model:

class Role extends Model
{
    public $timestamps = FALSE;
    // ... 其他的属性和方法
}

2. Modify the default list of timestamps

If the current What should I do if I am using a non-Laravel database and my timestamp column is named differently? Perhaps, they are called create_time and update_time respectively. Congratulations, you can also define it like this in the model:

class Role extends Model
{
    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';

3. Modify the timestamp date/time format

The following content refers to the official Laravel documentation:

By default, the timestamp is automatically formatted as 'Y-m-d H:i:s'. If you need a custom timestamp format, you can set the $dateFormat property in your model. This property determines the format in which the date is stored in the database and when serialized into an array or JSON:

class Flight extends Model
{
    /**
     * 日期时间的存储格式
     *
     * @var string
     */
    protected $dateFormat = 'U';
}

4. Many-to-many: Intermediate table with timestamp

When in a many-to-many association, the timestamp will not be automatically filled in, such as the intermediate table role_user between the user table users and the role table roles.

In this model you can define the relationship like this:

class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}

Then when you want to add a role to the user, you can use it like this:

$roleID = 1;
$user->roles()->attach($roleID);

By default, this middle The table does not contain timestamps. And Laravel will not try to automatically populate created_at/updated_at

but if you want to automatically save timestamps, you need to add created_at/updated_at in the migration file, and then add ->withTimestamps() in the model's association ;

public function roles()
{
    return $this->belongsToMany(Role::class)->withTimestamps();
}

5. Use latest() and oldest() for timestamp sorting

There are two "shortcut methods" for using timestamp sorting.

Instead:

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

This is faster:

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

By default, latest() uses created_at sorting.

Correspondingly, there is an oldest(), which will be sorted like created_at ascending

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

Of course, you can also use other specified fields to sort. For example, if you want to use updated_at, you can do this:

$lastUpdatedUser = User::latest('updated_at')->first();

6. Do not trigger the modification of updated_at

Whenever an Eloquent record is modified, it will Automatically maintain the updated_at field using the current timestamp, which is a great feature.

But sometimes you don’t want to do this. For example: when adding a certain value, you think this is not a “whole row update”.

So, you can do the same as above - just disable timestamps, remember this is temporary:

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

7. Only update timestamps and associated timestamps

Contrary to the previous example, maybe you need to update only the updated_at field without changing other columns.

So, the following writing method is not recommended:

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

You can use a faster method:

$user->touch();

Another situation, sometimes you not only want to update the current model updated_at, also want to update the records of superior relationships.

For example, if a comment is updated, then you want to update the updated_at of the post table.

Then, you need to define the $touches attribute in the model:

class Comment extends Model {
    protected $touches = ['post'];
    public function post()
    {
        return $this->belongsTo('Post');
    }
}

8. The timestamp field is automatically converted to the Carbon class

The last tip, But more like a reminder because you should already know it.

By default, the created_at and updated_at fields are automatically converted to $dates,

so you don't need to convert them to Carbon instances to use Carbon's methods.

For example:

$user->created_at->addDays(3);
now()->diffInDays($user->updated_at);

That’s it, a quick but hopefully helpful tip!

For more technical articles related to the laravel framework, please visit the laravel tutorial column!

The above is the detailed content of 8 Tips for Using Laravel Model Timestamps. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Laravel logs and error monitoring: Sentry and Bugsnag integrationLaravel logs and error monitoring: Sentry and Bugsnag integrationApr 30, 2025 pm 02:39 PM

Integrating Sentry and Bugsnag in Laravel can improve application stability and performance. 1. Add SentrySDK in composer.json. 2. Add Sentry service provider in config/app.php. 3. Configure SentryDSN in the .env file. 4. Add Sentry error report in App\Exceptions\Handler.php. 5. Use Sentry to catch and report exceptions and add additional context information. 6. Add Bugsnag error report in App\Exceptions\Handler.php. 7. Use Bugsnag monitoring

Why is Laravel still the preferred framework for PHP developers?Why is Laravel still the preferred framework for PHP developers?Apr 30, 2025 pm 02:36 PM

Laravel remains the preferred framework for PHP developers as it excels in development experience, community support and ecosystem. 1) Its elegant syntax and rich feature set, such as EloquentORM and Blade template engines, improve development efficiency and code readability. 2) The huge community provides rich resources and support. 3) Although the learning curve is steep and may lead to increased project complexity, Laravel can significantly improve application performance through reasonable configuration and optimization.

Laravel Live Chat Application: WebSocket and PusherLaravel Live Chat Application: WebSocket and PusherApr 30, 2025 pm 02:33 PM

Building a live chat application in Laravel requires using WebSocket and Pusher. The specific steps include: 1) Configure Pusher information in the .env file; 2) Set the broadcasting driver in the broadcasting.php file to Pusher; 3) Subscribe to the Pusher channel and listen to events using LaravelEcho; 4) Send messages through Pusher API; 5) Implement private channel and user authentication; 6) Perform performance optimization and debugging.

Laravel Cache Optimization: Redis and Memcached Configuration GuideLaravel Cache Optimization: Redis and Memcached Configuration GuideApr 30, 2025 pm 02:30 PM

In Laravel, Redis and Memcached can be used to optimize caching policies. 1) To configure Redis or Memcached, you need to set connection parameters in the .env file. 2) Redis supports a variety of data structures and persistence, suitable for complex scenarios and scenarios with high risk of data loss; Memcached is suitable for quick access to simple data. 3) Use Cachefacade to perform unified cache operations, and the underlying layer will automatically select the configured cache backend.

Laravel environment construction and basic configuration (Windows/Mac/Linux)Laravel environment construction and basic configuration (Windows/Mac/Linux)Apr 30, 2025 pm 02:27 PM

The steps to build a Laravel environment on different operating systems are as follows: 1.Windows: Use XAMPP to install PHP and Composer, configure environment variables, and install Laravel. 2.Mac: Use Homebrew to install PHP and Composer and install Laravel. 3.Linux: Use Ubuntu to update the system, install PHP and Composer, and install Laravel. The specific commands and paths of each system are different, but the core steps are consistent to ensure the smooth construction of the Laravel development environment.

What is the difference between php framework laravel and yiiWhat is the difference between php framework laravel and yiiApr 30, 2025 pm 02:24 PM

The main differences between Laravel and Yii are design concepts, functional characteristics and usage scenarios. 1.Laravel focuses on the simplicity and pleasure of development, and provides rich functions such as EloquentORM and Artisan tools, suitable for rapid development and beginners. 2.Yii emphasizes performance and efficiency, is suitable for high-load applications, and provides efficient ActiveRecord and cache systems, but has a steep learning curve.

Laravel e-commerce system practice: Product management Payment integrationLaravel e-commerce system practice: Product management Payment integrationApr 30, 2025 pm 02:21 PM

Laravel is suitable for developing e-commerce systems because it can quickly build efficient systems and provide an artistic development experience. 1) Product management realizes CRUD operation and classification association through EloquentORM. 2) Payment integration handles payment requests and exceptions through Stripe API to ensure the security and reliability of the payment process.

Recommended Laravel's best expansion packs: 2024 essential toolsRecommended Laravel's best expansion packs: 2024 essential toolsApr 30, 2025 pm 02:18 PM

The essential Laravel extension packages for 2024 include: 1. LaravelDebugbar, used to monitor and debug code; 2. LaravelTelescope, providing detailed application monitoring; 3. LaravelHorizon, managing Redis queue tasks. These expansion packs can improve development efficiency and application performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function