Why is toJSON returning incorrect value

Byakku

if I run the following:

App\User::selectRaw('country as id, COUNT(*) as value')->groupBy('country')->get()

I get the correct output:

all: [ App\User {#705 id: "UK", value: 2,},],}

However when I run

App\User::selectRaw('country as id, COUNT(*) as value')->groupBy('country')->get()->toJSON()

it seems to flip the id value to 0:

[{"id":0, "value":2}]

now what's interesting is if I convert it so that I don't alias the country field I get the correct output:

[{"country":"UK", "value":2}]

I need to have the field returned as id but can't seem to work out why it's doing this

patricus

When you call toJson() on the model, if the $incrementing property is true, Laravel will automatically attempt to cast the $primaryKey field to the $keyType type. If you have not overridden any of these values, that means the id field will get cast to an int during the json generation.

In your select, you named your country field as id, so when you generate the json, it attempts to cast this value (UK) to an int, which of course is 0.

You can change your select statement to not name the field id, or you can work around this functionality in a ton of different ways, either modifying model properties before and after the call to toJson(), or by overriding the getCasts() method to avoid this functionality altogether.

Edit

Without knowing your codebase or your use cases, I would say the most flexible solution for you would be to add a new method to your App\User model, something like:

public function toJsonCustom($options = 0)
{
    $incrementing = $this->getIncrementing();

    $this->setIncrementing(false);

    $json = $this->toJson($options);

    $this->setIncrementing($incrementing);

    return $json;
}

Then, you call your custom toJson method instead of the original one:

App\User::selectRaw('country as id, COUNT(*) as value')
    ->groupBy('country')
    ->get()
    ->toJsonCustom();

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related