I want only use created_at , how to do it?
I know:
This can custom timestamps name
const CREATED_AT = \'created\';
const UPDATED_AT = \'updat
I solved by adding default value CURRENT_TIMESTAMP
in my database for the column created_at
. And In my model I use this below code
public $timestamps = false;
protected $dates = ['created_at'];
I hope this method works in all versions of laravel.
In Laravel 5.7, this was enough for me to have it work:
In migration:
$table->timestamp('created_at')->nullable();
instead of classic $table->timestamp('created_at');
In model:
const UPDATED_AT = null;
My solution:
class CreatePostsTable extends Migration {
public function up() {
Schema::create('posts', function(Blueprint $table){
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
});
}
This works for me
A solution that is simple, decoupled, and reusable is to use a Model Observer. The idea is to capture the creating
event and fill the created_at
attribute. This method may be used by any number of models without having to repeat code or using unofficial tricks. Most importantly, it closely resembles the internal mechanics of the Model class, thus avoiding unexpected errors.
1) Create SetCreatedAt
observer in App\Observers
:
namespace App\Observers;
use Illuminate\Database\Eloquent\Model;
class SetCreatedAt
{
/**
* Sets created_at when creating the model.
*
* @param Model $model
* @return void
*/
public function creating(Model $model)
{
$model->setCreatedAt($model->freshTimestamp());
}
}
2) On App\Providers\AppServiceProvider
inside the boot
method add the following line for each of the models that you want the created_at
to be generated for:
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// Replace OrderLog with your model
OrderLog::observe(SetCreatedAt::class);
}
3) On your models, the only thing that you have to do is disable the timestamps:
// Disable timestamps on the model
public $timestamps = false;
Tested with Laravel 5.3, but it should work with previous versions as well.
Good luck!
In 5.4, the problem it gives is that it also doesn't populate updated_at field even after update (Eloquent update).
instead add this method
public function setUpdatedAtAttribute($value)
{
// auto disable update_at in inserts
}
My solution for this is using a new __construct
method.
See:
class MyModel extends Eloquent {
public $timestamps = false;
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->attributes['created_at'] = $this->freshTimestamp();
}
}