Home > Enterprise >  How to automatically cast a Model attribute before inserting or updating in Laravel Eloquent
How to automatically cast a Model attribute before inserting or updating in Laravel Eloquent

Time:04-20

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

CodePudding user response:

Step : Define accessor for that attributes.

Example:

protected $casts = ['input_params']; 

public function getInputParamsAttribute($input_params)
{
    return json_decode($input_params);
}

CodePudding user response:

In this situation, I recommend you to :

  1. Type your input_params database field as JSON. You can use Laravel migration for that :
$table->json('input_params');
  1. Cast your property input_params as array like 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)

  • Related