0

Pretty straightforward, in laravel I can't give longText or text fields a default value, given a field named "body" where body will probably have some text or html, how can I give it a default value in mysql?

gabogabans
  • 3,035
  • 5
  • 33
  • 81
  • 1
    I think it's not related to Laravel, plz check https://stackoverflow.com/questions/3466872/why-cant-a-text-column-have-a-default-value-in-mysql note that someone suggested to use trigger – Abdel-aziz hassan Aug 04 '20 at 20:15
  • 1
    you can set default values via Laravel on those fields, perhaps your DB has the issue – lagbox Aug 04 '20 at 20:17
  • 1
    Does this answer your question? [Why can't a text column have a default value in MySQL?](https://stackoverflow.com/questions/3466872/why-cant-a-text-column-have-a-default-value-in-mysql) – N69S Aug 04 '20 at 20:26

1 Answers1

0

As stated in the comments, mysql has limitations around defaults and texts. Instead you can set it through code. Before anything is saved to the database, the creating event is triggered. You can hook into this and set the default value on the model using the boot function.

class YourModel
{
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->body = '<body></body>';
        });
    }
}

This can also be done through observers, which is a little more comprehensive. Avoids doing to much logic in the boot method(), which quickly can become crowded.

mrhn
  • 17,961
  • 4
  • 27
  • 46