Search code examples
laraveltimestampdefaultunix-timestamp

Laravel: set timestamps from datetime to now as int


I am creating a Laravel application. Earlier I used to design the database with the datetime datatypes for created_at and updated_at, but a friend of mine suggested me that I should use timestamp instead of datetime because it's good with different timezones.

Is this a good idea to use timestamp instead of datetime format? Will there be any performance issues? If "No" then how can we change the default format of timestamps from datetime to timestamp globally in a laravel application.

For example (default):

$model->created_at = "yyyy-mm-dd h:i-s";
$model->updated_at = "yyyy-mm-dd h:i-s";

Integer timestamp:

$model->created_at = 1523246567;
$model->updated_at = 1523246567;

Solution

  • Unfortunately, I'm not able to answer your first two questions, but Laravel does provide an easy way to change the format your dates are stored in.

    The Date Mutators documentation says that one can set the $dateFormat property on your model like this:

    /**
     * The storage format of the model's date columns.
     *
     * @var string
     */
    protected $dateFormat = 'U';
    

    The 'U' format would be "Seconds since the Unix Epoch." More formats are available in the php date documentation.

    You would also need to change your model's migration. Replace $table->timestamps(); with $table->unsignedInteger('created_at'); and $table->unsignedInteger('updated_at');.

    To use a specific date format "globally", i.e. for all of your models, you could either set the date format on a base model and let all of your models inherit that model, or use a trait. See this question for an example.