'How to automatically cast a Model attribute before inserting or updating in Laravel Eloquent
Currently, I'm using the JSON Casting defined in my Model
protected $casts = ['input_params'=>'json'];
When retrieving data I'm able to get the input_param attribute as a JSON. But when I'm inserting or updating a row the attribute is being saved as string. I still need to use JSON decode to make sure that it will be saved as JSON.
Does the Laravel model have an equivalent for this code that can be defined on the Model?
$data['input_params'] = json_decode($data['input_params'], true);
Solution 1:[1]
In this situation, I recommend you to :
- Type your
input_paramsdatabase field as JSON. You can use Laravel migration for that :
$table->json('input_params');
- Cast your property
input_paramsasarraylike that :
protected $casts = ['input_params' => 'array'];
If you do this, Laravel will automatically save your array into JSON format and cast your JSON stored data to array when you will retrieve them. It is a convenient way to manipulate your data without manage json encode and decode. You can find more info here (Laravel 9)
Solution 2:[2]
Step : Define accessor for that attributes.
Example:
protected $casts = ['input_params'];
public function setInputParamsAttribute($input_params)
{
return json_decode($input_params);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Théo Champion |
| Solution 2 |
