1

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 Answer 1

1

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),
    );
}
Sign up to request clarification or add additional context in comments.

3 Comments

JSON is string, not array. Not sure if laravel knows that you are trying to cast JSON to array.
What? Laravel documentations says the json fields from DB are handled by casting to array. What are you talking about?!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.