1

in my laravel app I have a Post "body" field of text type, I'm trying to give the field a default value like "This sis the default text for a blog post, feel free to change it" but mysql is throwing an error.

$table->text('body')->default('This is the default text for a blog post, feel free to change it.');

This isn't working...

According to docs BLOB/TEXT fields CAN'T have default values, this is pretty weird tbh.

https://dev.mysql.com/doc/refman/5.7/en/blob.html

I guess I could change the field type from text to string but afaik string won't have as many characters as string type and I knpw for certain that my Blog posts will be loooong. How could I approach this?

Thanks in advance.

gabogabans
  • 3,035
  • 5
  • 33
  • 81

3 Answers3

1

You can use Accessors & Mutators
Here is an example for setting default value for body
What it does is that every time your model is going to save in database it checks if value is null then it sets your default value
Just put below code into your model.

public function setBodyAttribute($value = null)
    {
        if (null === $value) {
            $this->attributes['body'] = 'default value';
        }

        $this->attributes['body'] = $value;
    }
AH.Pooladvand
  • 1,944
  • 2
  • 12
  • 26
0

you can set it to nullable $table->text('body')->nullable(true); And in your view just give it a default text if it is NULL.

Domposter
  • 19
  • 6
0

In mysql you can't give text default value. Solutions:

  • Convert it to varchar ( You can have max 255 characters in one row)
  • Give default value with code ( during creating, after creating, default placeholder text ... )
Malkhazi Dartsmelidze
  • 4,783
  • 4
  • 16
  • 40