1

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?

5
  • 3
    May I ask why you would want to save empty string rather than null? You could setup accessors to return empty strings if the value is null in the database. laravel.com/docs/5.8/eloquent-mutators I only say this because from a data perspective storing empty strings instead of nulll values leads to data discrepancies. As in, was the data stored intended to be an empty string or because the value was an empty string. Commented Aug 30, 2019 at 13:58
  • agreed but how i can use accessors to implement this functionality? Commented Aug 30, 2019 at 14:05
  • @syed1234 you can't do it with accessors since create() like insert() ignores them. Commented Aug 30, 2019 at 14:09
  • How about setting the default of the columns in the database to an empty string? Commented Aug 30, 2019 at 14:20
  • Isn't that why it's an accessor and not a mutator? If he stores them null like he already is when he accesses the value he converts null into the empty string assuming for his frontend. However, I do see what you mean by passing what is returned from the create method. This is where you would want to use a transformer. Spatie and Freek have a great package for this github.com/spatie/laravel-fractal Commented Aug 30, 2019 at 14:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.