There is an issue when updating a model with a property cast as an array.
agrism opened this issue ยท 3 comments
agrism commented
Further details on the issue: When you try to update a model that uses a property cast as an array, Laravel throws an ErrorException with the message Array to string conversion
.
PHP version: 8.1
Laravel version: 8.83.27
If you'd like to reproduce the error, follow these steps.
- Make a Model:
namespace App\Models;
use Alvin0\RedisModel\Model;
/**
* @property string $id
* @property array $payload
*/
class MyModel extends Model
{
protected $primaryKey = 'id';
protected $subKeys = [
'payload',
];
protected $fillable = [
'payload',
];
protected $casts = [
'payload' => 'array'
];
public $incrementing = true;
protected $table = "my_models";
}
- Test the model:
$notifyIfPayloadNotArray = function(\App\Models\MyModel $model): void
{
if(!is_array($model->payload)){
dump('status not array');
}
};
$model = new \App\Models\MyModel;
$model->payload = ['a' => 1];
$notifyIfPayloadNotArray($model);
$model->save();
$notifyIfPayloadNotArray($model);
$model->payload = ['a' => 2];
$notifyIfPayloadNotArray($model);
$model->save(); // ---> ErrorException: Array to string conversion
alvin0 commented
Thank you for your contribution to the source code!.
However, I'm feeling uneasy about using the subkey as an array because it might lead to data retrieval issues. I will rewrite a data casting function before insertion and update based on your code to improve the array and enum.
Thank you very much for your significant contribution.