Laravel 5 how to handle created_at automatically but not update_at

as the laravel docs say the eloquent can take care of the created_at and updated_at files, what if I want laravel to only take care of created_at and leave update_at?

+3


source to share


3 answers


Eloquent handles timestamps in updateTimestamps()

:

protected function updateTimestamps()
{
    $time = $this->freshTimestamp();

    if ( ! $this->isDirty(static::UPDATED_AT))
    {
        $this->setUpdatedAt($time);
    }

    if ( ! $this->exists && ! $this->isDirty(static::CREATED_AT))
    {
        $this->setCreatedAt($time);
    }
}

      

You can simply override this function in your model and remove the part updatedAt

:

protected function updateTimestamps()
{
    $time = $this->freshTimestamp();

    if ( ! $this->exists && ! $this->isDirty(static::CREATED_AT))
    {
        $this->setCreatedAt($time);
    }
}

      




Or you can just override setUpdatedAt

, although you might want to keep this intentionally for setting the value:

public function setUpdatedAt($value)
{
    // do nothing
}

      

+5


source


One way to achieve the above is to change the model events. Add the following method to your model.

public static function boot()
{
    public $timestamps = false;
    parent::boot();

    static::creating(function($model) {
        $dateTime = new DateTime;
        $model->created_at = $dateTime->format('m-d-y H:i:s');
        return true;
    });

    static::updating(function($model) {
        $dateTime = new DateTime;
        $model->updated_at = $dateTime->format('m-d-y H:i:s');
        return true;
    });
}

      



You can now access the model creation and update events. Within these events, you can do whatever you want, in your case, you can change the timestamps. For more information on model events see the Laravel documentation Model Events

0


source


All or nothing for functionality outside the box.

By replicating the for-only functionality created_at

, you can use eloquent events. For each of your models, you can do the following

class MyModel extends Eloquent
{

    protected $timestamps = false;

    public static function boot()
    {
        parent::boot();

        static::creating(function($model)
        {
            $model->created_at = Carbon::now();
        });
    }

}

      

Every time a new model is created, this sets the column created_at

to the current time using Carbon.

0


source







All Articles