Sanz
Posted on July 7, 2020
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';
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;
}
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';
}
Order Timestamp latest and oldest
User can order data by timestamp using two shortcut methods which are:
User::latest()->get();
The above code is for getting latest time. As for getting oldest timestamp, the code is;
User::oldest()->get();
If you are interested, there are a lot more of these in https://laravelproject.com/laravel-timestamp-tricks/
Posted on July 7, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.