Home > Net >  Laravel 9 - casting json column from/to array
Laravel 9 - casting json column from/to array

Time:07-27

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');
}

CodePudding user response:

You need to rewrite getters and setters for the field. https://laravel.com/docs/9.x/eloquent-mutators#defining-an-accessor https://laravel.com/docs/9.x/eloquent-mutators#defining-a-mutator

You need something similar to:

protected function incrementoPorPersona(): Attribute
{
    return Attribute::make(
        get: fn ($value) => json_decode($value, true),
        set: fn ($value) => json_encode($value),
    );
}
  • Related