Laravel 9 - casting json column from/to array

Viewed 123

I'm trying to cast a json column named "incremento_por_persona" but always retun a string.

I add a cast on my "Tarifa" model:

protected $casts = [
    'incremento_por_persona' => 'array'
];

On controller, I have an array with some data:

        foreach ($request->minimoPersonas as $key => $value) {
            $incrementosPorPersona[$key]['minimo_personas'] = $value;
            $incrementosPorPersona[$key]['maximo_personas'] = $request->maximoPersonas[$key];
            $incrementosPorPersona[$key]['precio_incremento'] = $request->precioIncremento[$key];
            $incrementosPorPersona[$key]['tipo_incremento'] = $request->tipoIncremento[$key];
        }

And save this array without encoding:

Tarifa->incremento_por_persona= $incrementosPorPersona;
Tarifa->save();

The result saved on this column is like this:

[{"minimo_personas":"1","maximo_personas":"2","precio_incremento":"12","tipo_incremento":"1"},{"minimo_personas":"2","maximo_personas":"3","precio_incremento":"13","tipo_incremento":"1"}]

The "tarifa" table is an intermediate table, so I collect the field through a model pivot. But it is always returning a string, I can't receive an array.

public function propiedades(){
    return $this->belongsToMany(Propiedad::class, Tarifa::class, 'info_tarifa_id', 'id')->withPivot('incremento_por_persona');
}
1 Answers
Related