Skip to content
Advertisement

default() is not working in laravel migration

I am creating a to do list using laravel, and I have a table with the columns below:

‘title’, ‘description’, ‘completed’, ‘id’

The ‘completed’ column is set automatically whenever I add a new task to my table, its default value is 0 and it’s being coded like this:

JavaScript

This column works perfectly fine, but when I try to give ‘description’ a default value (by leaving an empty input for description), it gives me a ‘Integrity constraint violation: 1048 Column ‘description’ cannot be null’ error.

The code I have written for ‘description’ column is the code below:

JavaScript

I tried the text() data type, but it gives me the same error.

I also tried using nullable() for this column, but the default value, ‘-‘ , doesn’t get added to the column and it returns a emtpy value.

The form I’m using to add the values looks like this:

JavaScript

My controller store method:

JavaScript

and the table create statement:

JavaScript

Advertisement

Answer

After seeing the create table statement and your store function. It looks like it is more likely that your store function is the problem here. Try this:

JavaScript

In your code you use mass assignment described in detail here

For mass assignment you should define your database fields to be mass assignable in your Model with protected $fillable = ['title','description','user_id'];

Your problem in specific tho is that laravel sets empty inputs to null according to answer in this question: Mass assignment won’t handle Null input even when default is set on migration.Any solution to this?

You should always validate the user input and laravel provides robust tools for doing just that: https://laravel.com/docs/7.x/validation

You also might wanna consider using laravels built-in default values or at least check if they are intervening with the data :How to set the default value of an attribute on a Laravel model

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement