Eloquent Model Timestamps

Migrations: Creating Timestamps Columns

The timestamps method creates created_at and updated_at TIMESTAMP equivalent columns.

Schema::create('articles', function (Blueprint $table) {

Creates created_at and updated_at columns.


Creates created_at and updated_at columns with timezone.


Creates created_at and updated_at columns with an optional millisecond precision (total digits).

$table->timestamps($precision = 0); 

Creates added_at TIMESTAMP column.

$table->timestamp('added_at', $precision = 0);

Migrations: Drop Timestamps Columns

Drop the created_at and updated_at columns.


Model: Updating Timestamps Columns

Automatically set timestamps values

When models are created or updated, Eloquent will automatically set the values of these columns.

Created_at and updated_at columns will be updated if you use Eloquent's save method.

$article->name = 'New Custom Name';

Updating timestamp mannualy

You can also update timestamps using this touch method. Column updated_at will be updated.


Update without touching updated_at

$article->name = 'New Custom Name';
$article->timestamps = false;

Model: Conventions

If you have not created created_at, or updated_at columns in the table then you must specify this in the model. Otherwise Eloquent will try to update these fields.

class Article extends Model
    public $timestamps = false;

Set the dateFormat property on your model to alter the format of your model's timestamps.

class Article extends Model
    protected $dateFormat = 'U';

You can use the CREATED AT and UPDATED AT variables on your model to alter the names of the columns used to store timestamps.

class Article extends Model
    const CREATED_AT = 'creation_date';
    const UPDATED_AT = 'updated_date';

Model: Relationships

Intermediate Table Columns

If you want your intermediate table to have created_at and updated_at timestamps that are automatically maintained by Eloquent, call the withTimestamps method when defining the relationship

class Articles extends Model
    public function tags() : BelongsToMany
        return $this->belongsToMany(Tag::class)->withTimestamps();

Touching Parent Timestamps

When a model has a belongsTo or belongsToMany relationship with another model, such as a Comment belonging to an Article, it can be useful to update the parent's timestamp when the child model is updated.

class Comment extends Model
    protected $touches = ['article'];
    public function article()
        return $this->belongsTo(Article::class);

Parent model timestamps will only be updated if the child model is updated using Eloquent's save method.

Touching Parent Timestamps doesn't work for ManyToMany relationships.

Eloquent: Query Builder

Sorting by created_at

Article::orderBy('created_at', 'desc')->get();
// or