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.
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...
In your Schema (migration), use
$table->integer('created_at');
$table->integer('updated_at');
instead of
$table->timestamps();
Replace the timestamp()
function in your models.
$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 {
}
For Laravel 4:
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');
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With