Reputation: 12383
I am having an issue with Laravel and default values. I created the field in my table like so:
$table->string('title', 255)->default('');
And in the model, I have a default set again using this:
protected $attributes = [
'title' => '',
];
Yet I am always getting this error:
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "title" violates not-null constraint DETAIL: Failing row contains (3dd07c7a-e3f3-4f20-8d16-0f066b219dc2, dsfs, sdfs, null, null, null, sdfs, null, 0, 0, 0, 0, 0, 0, null, null, null). (SQL: insert into "users" ("title", "first_name", "last_name", "email", "business_unit", "linkedin_profile") values (, dsfs, sdfs, sdfs, , ) returning "user_id")
My abbreviated save action (example without validation) is the following:
$data = Input::all();
$user = new Users($data);
$user->save();
The following is the $data:
array (size=12)
'_token' => string '0EI9JGmgiNDAqmv83pdQZaktyWNLiX3GB9JQSfvA' (length=40)
'first_name' => string 'ads' (length=3)
'last_name' => string 'asd' (length=3)
'email' => string 'asd' (length=3)
'title' => null
'business_unit' => null
'linkedin_profile' => null
'is_admin' => string '0' (length=1)
'is_employee' => string '0' (length=1)
'is_manager' => string '0' (length=1)
'is_trainer' => string '0' (length=1)
'rt' => string '/users' (length=6)
How come my default value is not being set?
Upvotes: 0
Views: 9476
Reputation: 3869
Because the 'title' key is in the provided array, it'll try to insert it: you should be able to insert null values.
You could use a mutator setTitleAttribute($val)
method in your Model class, or simply unset the 'title' array key if the value is empty before inserting. You could also filter using collection helpers or array_filter to remove unset all null values.
Upvotes: 0
Reputation: 14921
The problem is that your database column does not allow null values for title.
You can allow them like this:
$table->string('title')->nullable()->default('');
Or even without the default to have it as NULL
by default:
$table->string('title')->nullable();
Otherwise, you have to make sure your title is not null.
If you don't want to allow null values and convert it automatically to empty string, you can add a mutator like this to your model:
public function setTitleAttribute($title)
{
$this->attributes['title'] = is_null($title) ? '' : $title;
}
For more information: https://laravel.com/docs/5.6/eloquent-mutators
Upvotes: 2