DEV Community

Sanz
Sanz

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

4 2

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/

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay