Juliatzin
Juliatzin

Reputation: 19695

Converting just one field to int (without comma) in a laravel Json Response

I am returning an eloquent model :

{
    "t": "2020-10-01T00:00:00Z",
    "meter_id": "30002",
    "operation_id": "ACC000000",
    "conso_prod": "Conso",
    "d": "14",
    "s": "Pamela",
    "timestep": 600000000000,
    "unit": "kW"
},

What I want is d to be a float, so, without "":

{
    "t": "2020-10-01T00:00:00Z",
    "meter_id": "30002",
    "operation_id": "ACC000000",
    "conso_prod": "Conso",
    "d": "14",
    "s": "Pamela",
    "timestep": 600000000000,
    "unit": "kW"
},

So, I used:

    return Response::json($raws, 200, [], JSON_NUMERIC_CHECK);

Which worked great fo d field.

But now, I have the field meter_id that has became a integer, and this one, I want it as a string:

Final result I would need:

{
    "t": "2020-10-01T00:00:00Z",
    "meter_id": "30002",
    "operation_id": "ACC000000",
    "conso_prod": "Conso",
    "d": 14,
    "s": "Pamela",
    "timestep": 600000000000,
    "unit": "kW"
},

I also tried to cast fields in the model:

  1. Casting d to float, didn't work
  2. Casting meter_id to string, didn't work neither

If possible, I would like to avoid using ->map() over result to manually cast the fields, as my collection can be quite big.

What should I do about it ?

Upvotes: 0

Views: 349

Answers (3)

Dan
Dan

Reputation: 5348

I suggest casting the whole object into a custom JsonResource. This way you have complete control over what gets outputted, how it gets transformed and how consistent it'll be when you change something within the model:

The Eloquent resource:

use Illuminate\Http\Resources\Json\JsonResource;

class AResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            't' => $this->t,
            'meter_id' => (string) $this->meter_id,
            'operation_id' => $this->operation_id,
            'conso_prod' => $this->conso_prod,
            'd' => (int) $this->d,
            's' => $this->s,
            'timestep' => (float) $this->timestep,
            'unit' => $this->unit,
        ];
    }
}

To transform a single model use

new AResource($raws);

and to transform a Eloquent collection use

AResource::collection($raws);

You can directly return the resource from the controller, it'll act as a response.

Upvotes: 2

Kamlesh Paul
Kamlesh Paul

Reputation: 12391

try Laravel cast

https://laravel.com/docs/8.x/eloquent-mutators#attribute-casting

protected $casts = [
    'meter_id' => 'string',
     'd' => 'integer',
];

Upvotes: 0

I suggest using intval() php function.

On the other side, i think you should consider using the map collection function to manipulate your array.

Upvotes: 0

Related Questions