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
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!