Original link: learnku.com/laravel/t/3… For discussion, head to the professional Laravel developer forum: learnku.com/Laravel

By default, the default data table for the Laravel Eloquent model has two fields: creATED_AT and updated_AT. Of course, we can do a lot of customization and implement a lot of interesting features. Here are some examples.


1. Disable the timestamp

Model::create($arrayOfValues); — you will see SQL error. Laravel could not find these two fields when created_AT/updated_AT was automatically populated.

To disable automatic timestamp filling, add a single property on the Eloquent Model:

class Role extends Model
{
    public $timestamps= FALSE; / /... Other properties and methods}Copy the code

2. Modify the default timestamp list

What if you’re currently using a non-Laravel database and your timestamp columns are named differently? Maybe they’re called create_time and update_time, respectively. Congratulations, you can also define this in the model:

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

Copy the code

3. Change the date/time format of the timestamp

The following is documented by 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 attribute in your model. This property determines the format in which the date is stored in the database and when serialized to an array or JSON:

Class Flight extends Model {/** * date-time storage format ** @var string */ protected$dateFormat = 'U';
}
Copy the code

Many-to-many: Intermediate tables with timestamps

Timestamps are not automatically populated in many-to-many associations, such as the middle table ROLE_USER for users and roles.

In this model you can define relationships as follows:

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

Then when you want to add a role to a user, you can use:

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

By default, this intermediate table does not contain timestamps. And Laravel doesn’t try to automatically populate created_AT/updated_AT

But if you want to save timestamps automatically, you need to add created_AT/updated_AT to the migration file and then add **->withTimestamps() to the model’s association; **

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

Copy the code

5. Uselatest()andoldest()Time stamp sort

There are two “shortcuts” to using timestamp sort.

Instead:

User::orderBy('created_at'.'desc')->get();
Copy the code

It’s faster:

User::latest()->get();
Copy the code

By default, latest() is sorted by created_at.

Corresponding to this is a simple (), which sorts created_at ascending this way

User::oldest()->get();
Copy the code

Of course, you can also sort using the other fields specified. For example, if you wanted to use updated_AT, you could do this:

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

6. Don’t triggerupdated_atThe modified

The current timestamp is automatically used to maintain the Updated_AT field whenever Eloquent records are modified, which is a great feature.

But sometimes you don’t want to do that, for example, when you increment a value and think it’s not a “whole row update.”

Well, you can do all of this — just disable timestamps and remember that this is temporary:

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

7. Update only the timestamp and associated timestamp

Contrary to the previous example, you might want to update only the UPDATed_AT field without changing the other columns.

Therefore, the following is not recommended:

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

You can use the faster method:

$user->touch();
Copy the code

On the other hand, sometimes you want to update not only the updated_AT of the current model, but also the parent record.

For example, if a comment is updated, you want to update updated_AT for the POST table as well.

So, 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 the code

8. Automatic timestamp field conversionCarbonclass

One 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; you can use the Carbon method instead.

Such as:

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

That’s it, quick but hopefully useful tip!

Original link: learnku.com/laravel/t/3… For discussion, head to the professional Laravel developer forum: learnku.com/Laravel