简体   繁体   中英

How to save empty string in database using Laravel

This is my controller code:

public function addEmployer(Request $request)
{
    $validator = UserValidations::validateEmployer($request->all());

    if ($validator->fails()) {
        return response(['status' => false, 'message' => 'Validation Errors', 'errors' => $validator->errors()->all()], 500);
    }

    try {

        $request->request->add(['created_by' => Auth::user()->id]);
        $employer = $this->employer->create($request->only($this->employer->getModel()->fillable));

        return response(['status' => true, 'message' => 'Employer added', 'data' => $employer], 200);

    } catch (\Exception $ex) {
        return response(['status' => false, 'message' => 'Validation Errors', 'errors' => $ex->getMessage()], 500);
    }
}

When I save I get null values and there is NULL in database because field type is nullable() ,
My Json response when I sent empty value

"first_name": "Adnan12",
"middle_name": null,
"last_name": null,
"street_address": null,
"suit_floor": null,
"city": null,
"state": null,
"zip": null,
"contact_person_first_name": null,
"contact_person_middle_name": null,
"phone_no": null,
"ext": null,
"cell_no": null,
"fax": null,
"email": null,
"comments": null,
"created_by": 9,
"updated_at": "2019-08-30 13:51:17",
"created_at": "2019-08-30 13:51:17",

I want empty string instead of NULL in json response. How I can achieve this functionality?

In App/Http/Kernel class you can find the \\Illuminate\\Foundation\\Http\\Middleware\\ConvertEmptyStringsToNull class that is assigned to the property $middleware .

This property is an array of all the global middlewares that run on every request.

You can:

  1. Remove or comment out that line so every string input is not converted to null if empty.
  2. Write your own middleware if you want to select the fields that could be empty string, something like that:
namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\TransformsRequest as Middleware;

class ConvertEmptyStringsToNull extends Middleware
{
    /**
     * The names of the attributes that should not be converted to null if empty.
     *
     * @var array
     */
    protected $except = [
        'middle_name',
        'last_name',
    ];

    protected function transform($key, $value)
    {
        if (in_array($key, $this->except, true)) {
            return $value;
        }
        return is_string($value) && $value === '' ? null : $value;
    }
}

Now you can replace \\Illuminate\\Foundation\\Http\\Middleware\\ConvertEmptyStringsToNull::class with your own App\\Http\\Middleware\\ConvertEmptyStringsToNull::class in the $middleware property of the App\\Http\\Kernel class .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM