pasadinhas
pasadinhas

Reputation: 363

Store dates using Eloquent/Laravel

What's a good way of storing a date in a Eloquent Model? I'm using PHP with Laravel framework.

class MyModel extends Eloquent {
  // I want a date field here... should it be:
  public $endTime = ?;
}

Should I use a integer timestamp which gets saved as an int? What's the behaviour if I use a Date object in a atributte and save that object?

Upvotes: 3

Views: 3004

Answers (1)

The Alpha
The Alpha

Reputation: 146191

If you are using migration then use $table->timestamp('endTime'), this will create a timestamp field by using endTime as it's name.

By default, Eloquent will convert the created_at, updated_at, and deleted_at columns to instances of Carbon, which provides an assortment of helpful methods, and extends the native PHP DateTime class. You may customize which fields are automatically mutated, and even completely disable this mutation, by overriding the getDates method of the model.

Add this method in your model:

public function getDates()
{
    return array('created_at', 'updated_at', 'deleted_at', 'endTime');
}

Laravel will take care of these fields and by default each of these fields will be an instance of Carbon object. Read about date mutators. In this case all methods of Carbon could be used on these fields.

Upvotes: 5

Related Questions