Laravel Timestamp Tricks

sanz

Sanz

Posted on July 7, 2020

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/

💖 💪 🙅 🚩
sanz
Sanz

Posted on July 7, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Enums e lang no Laravel
webdev Enums e lang no Laravel

September 17, 2024

Laravel Auth Routes Tutorial
laravel Laravel Auth Routes Tutorial

September 14, 2024

Baby Steps Learning Laravel
webdev Baby Steps Learning Laravel

August 30, 2024