Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make my own timestamp method in Laravel?

Typically, the Laravel platform have a $table->timestamps(); in migration..., it generate two datetime fields, But I would like to implement my own timestamps or, maybe call unix_timestamps(). I would like to have two fields named created_at, and updated_at, and which store the unix timestamps, how can I implement it? Thanks.

like image 834
DNB5brims Avatar asked Dec 02 '22 23:12

DNB5brims


2 Answers

You don't have to use Laravel's timestamp helpers, but they are convenient. There are some good ways of working with string timestamps now too, including PHP's DateTime class. But I digress, to use unix timestamps...

  1. In your Schema (migration), use

    $table->integer('created_at');
    $table->integer('updated_at');
    

    instead of

    $table->timestamps();
    
  2. Replace the timestamp() function in your models.

  3. Keep $timestamps = true in your models.

Here's an example base model which you could use, and extend instead of Eloquent on your models:

// models/basemodel.php
class BaseModel extends Eloquent {

    /**
     * Indicates if the model has update and creation timestamps.
     *
     * @var bool
     */
    public static $timestamps = true;

    /**
     * Set the update and creation timestamps on the model.
     */
    public function timestamp()
    {
        $this->updated_at = time();

        if ( ! $this->exists) $this->created_at = $this->updated_at;
    }
}

// models/thing.php
class Thing extends BaseModel {

}
like image 162
Phill Sparks Avatar answered Dec 11 '22 09:12

Phill Sparks


For Laravel 4:

  • override the freshTimestamp() method in your Eloquent model
  • use integers in migration file in stead of timestamps

models/product.php

class Product extends Eloquent {
    protected $table = 'products';

    public function freshTimestamp()
    {
        return time();
    }
}

Laravel 4 also mutates all dates/timestamps to Carbon instances (Documented here)

Which means you also need to overwrite the getDates() method in order to prevent Carbon ruining your timestamp before insertion.

public function getDates()
{
    return array();
}

database/migrations/2013_04_20_125823_create_products_table.php :

public function up()
{
    Schema::create('products', function(Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('created_at');
        $table->integer('updated_at');
    });
}
like image 31
Dirk Avatar answered Dec 11 '22 09:12

Dirk