2

I have been using mass assignment a lot. I recently came across this issue, where I create fillable, and also defaults for null values, but on using mass assignment, if my inputs are empty, it returns a "Cannot Be Null" Error.

My Model

protected $fillable = ['name','status'];

My Controller

$this->model->create($request->all());

My Migration

$table->boolean('status')->default(0);

Shouldn't the above mean that when I provide nothing on the input field status, it should default to 0? But column can't be null is thrown.

Is there any solution to this?

Lakhwinder Singh
  • 5,536
  • 5
  • 27
  • 52

2 Answers2

1

I've run into this myself. Take a look in your app\Http\Kernel.php file. There is a Laravel middleware that is converting your empty inputs into null values. So, even though you've correctly got the mass assignment set up, and the migration defaulting to 0, this middleware is changing the value before it gets to those points. The code you are looking for is similar to:

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, // <<-- This one
];

You can remove it, or leave it in and write a method to compensate for all inputs. I simply removed this and then set a mutator to do what the middleware did for those inputs I wanted to be null.

HTH

Watercayman
  • 7,970
  • 10
  • 31
  • 49
  • yes, but I am using boolean, and when I don't convertEmptyStringToNull, I am passing an empty string, for boolean, and still doesn't default to 0 from my migration. What can be done for this? – Manishbasnyat182 May 29 '19 at 06:19
  • Add a mutator on the model. If the value comes in empty or null, set the value to 0. – Watercayman May 29 '19 at 14:59
1

I guess you have the problem because of ConvertEmptyStringsToNull middleware which was added to laravel >= 5.4. This middleware convert all empty strings to null. So if You don't set any value to status field it will be null. Your migration isn't ->nullable() so there is thrown error Cannot Be Null.

You can resolve it like this:

$all = $request->all();

if(is_null($request->get('status')))
{
     unset($all['status']);
}

$this->model->create($all);
yrv16
  • 2,205
  • 1
  • 12
  • 22