DEV Community

Sanz
Sanz

Posted on • Edited on • Originally published at laravelproject.com

Laravel Timestamp Tricks

There are various interesting things that a user can do with laravel timestamp. Some of which are:

Change Timestamp Column Name

If the user has non-laravel database as well as differently named timestamp column then there is no need to panic.

Lets say user has created_time and updated_time in timestamp column. User can specify it in model:

class Role extends Model
{
    const CREATED_AT = 'created_time';
    const UPDATED_AT = 'updated_time';
Enter fullscreen mode Exit fullscreen mode

Disable Timestamps

If user doesn’t have time column but tries something like Model::create($arrayOfValues). As a result, he/she will get a SQL error.

For solving this problem, user can disable automatic timestamp by adding one property.

class Role extends Model
{
    public $timestamps = FALSE;
}
Enter fullscreen mode Exit fullscreen mode

Before Laravel7, the datetime would be in format of 2019-12-02 20:01:00. However now in laravel7, date time is in format of 2019-12-02T20:01:00.283041Z.

So, if you need to customize timestamp format, set the $dateFormat property on your model which determines how attributes are stored in database.

class Flight extends Model
{
    /**
     * The storage format of the model's date columns.
     *
     * @var string
     */
    protected $dateFormat = 'U';
}
Enter fullscreen mode Exit fullscreen mode

Order Timestamp latest and oldest

User can order data by timestamp using two shortcut methods which are:

User::latest()->get();
Enter fullscreen mode Exit fullscreen mode

The above code is for getting latest time. As for getting oldest timestamp, the code is;

User::oldest()->get();
Enter fullscreen mode Exit fullscreen mode

If you are interested, there are a lot more of these in https://laravelproject.com/laravel-timestamp-tricks/

Top comments (0)