Table of Contents
1. Disable timestamp
2. Modify the default list of timestamps
3. Modify the timestamp date/time format
6. Do not trigger the modification of updated_at
Home PHP Framework Laravel [Organization and sharing] 8 tips for using Laravel model timestamps

[Organization and sharing] 8 tips for using Laravel model timestamps

Sep 22, 2022 pm 08:18 PM
php laravel

Below, the Laravel Tutorial column will share with you 8 tips on how to use Laravel model timestamps. See if you have never used them. If not, come and collect them. I hope it will be helpful to everyone!

[Organization and sharing] 8 tips for using Laravel model timestamps

By default, the Laravel Eloquent model default data tables include created_at and updated_at Two fields. Of course, we can make a lot of custom configurations and implement many interesting functions. Here are some examples.


1. Disable timestamp

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

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

class Role extends Model
{
    public $timestamps = FALSE;

    // ... 其他的属性和方法
}
Copy after login

2. Modify the default list of timestamps

What if you are currently using a non-Laravel type of database, that is, your 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';
Copy after login

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 to customize the 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';
}
Copy after login

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# of 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);
    }
}
Copy after login
Then when you want to add a role to the user, you can use it like this:

$roleID = 1;
$user->roles()->attach($roleID);
Copy after login
By default, this middle Table

does not contain timestamp . And Laravel will not try to automatically populate created_at/updated_at

but if you want to automatically save the timestamp, you need to add

created_at/updated_at in the migration file , and then add ->withTimestamps();

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

5. Use latest() Andoldest()Perform timestamp sorting

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

Instead:

User::orderBy('created_at', 'desc')->get();
Copy after login
This is faster:

User::latest()->get();
Copy after login
By default,

latest() uses created_at sorting.

Correspondingly, there is an

oldest(), which will be sorted like this created_at ascending

User::oldest()->get();
Copy after login
Of course, you can also use other specified fields Sort. For example, if you want to use

updated_at, you can do this:

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

6. Do not trigger the modification of updated_at

Whenever an

Eloquent record is modified, the current timestamp will be automatically used to maintain the updated_at field, 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”.

Then you can do the same as above - just disable

timestamps and remember this is temporary:

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

7. Update times only Stamps and associated timestamps

Just the opposite of the previous example, maybe you need to update only the

updated_at field without changing the other columns.

So, the following writing method is not recommended:

$user->update(['updated_at' => now()]);
Copy after login
You can use a faster method:

$user->touch();
Copy after login
Another situation, sometimes you not only want to update the current model The

updated_at also hopes to update the record of the superior relationship.

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');
    }

}
Copy after login

8. Timestamp field automatic conversionCarbonClass

One last tip, but more like a reminder since 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 instance, that is, the method of Carbon can be used.

For example:

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

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

English original address: https://laraveldaily.com/8-tricks-with-laravel-timestamps/

Translation address: https://learnku.com/laravel/ t/39353

The above is the detailed content of [Organization and sharing] 8 tips for using Laravel model timestamps. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

CakePHP Logging CakePHP Logging Sep 10, 2024 pm 05:26 PM

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide

See all articles