0

I want to set default value to the last day of year in laravel migration column, for example "31-12-2021" but I want year to be changed automatically every year

N69S
  • 16,110
  • 3
  • 22
  • 36
Behruz
  • 19
  • 1
  • Does this answer your question? [MySQL: adding current year as a default value for a field 'year'](https://stackoverflow.com/questions/301937/mysql-adding-current-year-as-a-default-value-for-a-field-year) – N69S Jun 14 '21 at 10:39
  • either do that on do it in the code at your insertion code. – N69S Jun 14 '21 at 10:40
  • I would like to do it in migration – Behruz Jun 14 '21 at 10:42
  • If you do want to do it in the migration (I wouldn't) check out the version of SQL you have and create a default value based on an SQL function. For example, DATEADD (dd, -1, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) +1, 0)) gets the last day of each current year. – Rob Anthony Jun 14 '21 at 18:23

1 Answers1

1

My understanding is that migration files are used to set table columns data types only, and the timestamps are supported data types inside the database.

So, you can't make a dynamic default value other than a timestamp.

I will suggest this logic inside your Model:

class User extends Eloquent {

    public $timestamps = false;

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

        static::creating(function ($model) {
            $model->created_at = //the calculation of the last day of the year
        });
    }

}

Edit: As @Andy commented you can get the last day of the year like:

$model->created_at = date("Y-m-d", strtotime("last day of december"));
Ali Ali
  • 1,756
  • 2
  • 15
  • 34