5 Tricks with Laravel Timestamps

Today, I would like to share some tricks for Laravel Timestamps. Let’s take a look.

1. Changing the Timestamps Column names

Sometimes, you might have to change the timestamps column names : created_at and updated_at. In that case, you can set them in the model as follows.

class Product extends Model{
	const CREATED_AT = ‘start_time’;
	const UPDATED_AT = ‘modify_time’;
}

2. Disabling the timestamps that are filled automatically by Laravel

You can disable the automatic filling timestamps in Eloquent model as follows.

class Product extends Model{
	public $timestamps = FALSE;
}

3. Using shortcuts for order by timestamps

You can use latest() instead of orderBy(‘created_at’, ‘desc’).

You can use oldest() instead of orderBy(‘created_at’, ‘asc’).

4. Updating data without updating updated_at

In some cases, you can update the data without touching ‘updated_at’ column as follows.

$product = Product::find(1);
$product→name = ‘product1’;
$product→timestamps = false;
$product→save();

5. Updating only ‘updated_at’ with short way

You can update only ‘updated_at’ as following.

Use

$product→touch();

instead of:

$product→update([‘updated_at’=>now()]);

This is all for now. Hope you enjoy that.

By Asahi



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム