1

I have a model with a number of fillable fields

class Customer extends Model
{
  protected $fillable = [...,'my_field'...]
}

I also have a controller to update this table with the following method:

public function update(Request $request, Customer $customer)
{
    error_log($request->all());
    $customer->update($request->all());
    return response()->json($customer, 200);
}

If I send a request with a body containing an empty string:

{
    ...
    "my_field": "",
    ...
}

this field will be stripped out by the $request->all() method resulting in an array like this:

Array
(
...
[my_field] =>
...
)

which then creates this error:

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'my_field' cannot be null

But it should not be null, I want it to be an empty string. What is the standart way to deal with this?

shaedrich
  • 5,457
  • 3
  • 26
  • 42
NDDT
  • 445
  • 1
  • 10
  • 27

1 Answers1

2

Laravel uses middleware to convert empty strings on a request to null. If you want to prevent this from happening, you should remove the \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class middleware entry from the $middleware array in App\Http\Kernel.php.

It is transformed in the following function in the ConvertEmptyStringsToNull Middleware:

/**
 * Transform the given value.
 *
 * @param  string  $key
 * @param  mixed  $value
 * @return mixed
 */
protected function transform($key, $value)
{
    return is_string($value) && $value === '' ? null : $value;
}

Note: you can also manually check and override the request values before you use it to update the $customer. Consider adding validation; then you can use the $request->validated() function instead of the $request->all() function to prevent mass assignment vulnerability.

Eric Landheer
  • 2,033
  • 1
  • 11
  • 25