Mass assignment won't handle Null input even when default is set on migration.Any solution to this?

拜拜、爱过 提交于 2021-01-28 07:25:24

问题


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?


回答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




回答2:


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);


来源:https://stackoverflow.com/questions/56353195/mass-assignment-wont-handle-null-input-even-when-default-is-set-on-migration-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!