Zlatan Omerovic
Zlatan Omerovic

Reputation: 4097

How to force int to string in Laravel JSON?

I've recently updated my server to a newer version of MySQL and PHP 7 for various reasons. On my previous instance, running PHP 5.5, Laravel's response()->json() always converted tinyint's into a string. Now running newer server software, it's returning me int's -as it should...

I'd have to change a lots of my codebase to either cast types / convert them into a string manually, whic I'm trying to avoid at the moment.

Is there a way to somehow force response()->json() to return int's as string's?

Upvotes: 1

Views: 3582

Answers (5)

Ivan Kolodii
Ivan Kolodii

Reputation: 31

The best solution for me is to to use attribute casting and Fractal transformers

Fractal transformers are extremely useful when you have complex responses with multiple relations included.

Upvotes: 0

sirbeagle
sirbeagle

Reputation: 76

If you don't want to modify a lot of code you could run response data through a quick and dirty function. Instead of going directory to JSON you should instead grab the data as a nested array. Then put it through a function like this:

function convertIntToString ($myArray) {
    foreach ($myArray as $thisKey => $thisValue) {
        if (is_array($thisValue)) {
            // recurse to handle a nested array
            $myArray[$thisKey] = convertIntToString($thisValue);
        } elseif (is_integer($thisValue)) {
            // convert any integers to a string
            $myArray[$thisKey] = (string) $thisValue;
        }
    }
    return $myArray;
}

The function will convert integers to strings and use recursion to handle nested arrays. Take the output from that and then convert it to JSON.

Upvotes: 0

oseintow
oseintow

Reputation: 7371

There is a way to cast integer into string in laravel

in your model you can cast id to string. Its as follows

protected $casts = [ 'id' => 'string' ];

But the downside is that you would have to do that for all Models.

Upvotes: 2

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

Is there a way to somehow force response()->json() to return int's as string's

I don't want to change the code base - do not want to cast types, convert it,

No. There's no option for that. You need to do that yourself if needed.

Upvotes: 2

leyduana
leyduana

Reputation: 159

You can typecast it to string:

return response->json(["data" => (string)1]);

Upvotes: -1

Related Questions