Search code examples
phplaraveleloquenttimestamp

How to remove "updated_at" while keeping the "created_at" in Eloquent ORM Laravel


In Laravel I have a model that is created only but not updated. So, I want to remove only the updated_at field. But the created_at field is required.

So how can I remove only the updated_at field while keeping the created_at field?


Solution

  • In your model add these two lines:

    public $timestamps = ["created_at"]; //only want to used created_at column
    const UPDATED_AT = null; //and updated by default null set
    

    second way:

    public $timestamps = false; //by default timestamp true
    

    add function like this:

    public function setCreatedAtAttribute($value) { 
        $this->attributes['created_at'] = \Carbon\Carbon::now(); 
    }
    

    from laravel 10 you can use withoutTimestamps() method

    $user = User::find(1);
    $user->withoutTimestamps(function () use ($user) {
        $user->update(['name' => 'John Doe']);
    });
    

    for more info about laravel timestamp see