Skip to content
Advertisement

How to convert null values to empty string in Laravel 5.6 json response?

I have this response from my Laravel 5.6:

JavaScript

It comes from this Laravel PHP code:

JavaScript

Is there any built-in function in Laravel 5.6 to change the null value to empty sting? I want to get back this json object:

JavaScript

Any idea?

Advertisement

Answer

If you don’t have any choice and you really need it, you can do this using a middleware.

Create a file named NullToBlank.php in the folder app/Http/Middleware with the following code:

JavaScript

This is the case when you need to change values only on the returned model, not on related models. In the case of returned + all the related models, then the condition if($output instanceof Model) changes to:

JavaScript

In your app/Http/Kernel.php make sure you add:

JavaScript

under $middleware.

This should do the trick. I haven’t tested it personally, I just did on the go, if you have problems, let me know.

Luca

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement