From cb62699418535ed3c90bad0525db5c191a3e2c61 Mon Sep 17 00:00:00 2001 From: balajidharma Date: Fri, 20 Dec 2024 21:01:15 -0500 Subject: [PATCH] Added validation on config --- README.md | 11 ++++++----- config/attributes.php | 11 ++++++----- src/Models/Attribute.php | 4 +++- 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index aff6a45..4a155a2 100644 --- a/README.md +++ b/README.md @@ -242,11 +242,12 @@ Disable or enable the value validation based on data type. ```php 'data_types' => [ - ['type' => 'string', 'cast' => 'string'], - ['type' => 'integer', 'cast' => 'integer'], - ['type' => 'boolean', 'cast' => 'boolean'], - ['type' => 'date', 'cast' => 'date'], - ['type' => 'json', 'cast' => 'array'], + ['type' => 'string', 'validation' => 'string', 'cast' => 'string'], + ['type' => 'integer', 'validation' => 'integer', 'cast' => 'integer'], + ['type' => 'float', 'validation' => 'numeric', 'cast' => 'float'], + ['type' => 'boolean', 'validation' => 'boolean', 'cast' => 'boolean'], + ['type' => 'date', 'validation' => 'date', 'cast' => 'date'], + ['type' => 'json', 'validation' => 'json', 'cast' => 'array'], ], ``` Support all the Eloquent [Attribute Casting](https://laravel.com/docs/eloquent-mutators#attribute-casting) diff --git a/config/attributes.php b/config/attributes.php index 22245e7..b26f886 100644 --- a/config/attributes.php +++ b/config/attributes.php @@ -12,10 +12,11 @@ 'validate_value_before_save' => true, 'data_types' => [ - ['type' => 'string', 'cast' => 'string'], - ['type' => 'integer', 'cast' => 'integer'], - ['type' => 'boolean', 'cast' => 'boolean'], - ['type' => 'date', 'cast' => 'date'], - ['type' => 'json', 'cast' => 'array'], + ['type' => 'string', 'validation' => 'string', 'cast' => 'string'], + ['type' => 'integer', 'validation' => 'integer', 'cast' => 'integer'], + ['type' => 'float', 'validation' => 'numeric', 'cast' => 'float'], + ['type' => 'boolean', 'validation' => 'boolean', 'cast' => 'boolean'], + ['type' => 'date', 'validation' => 'date', 'cast' => 'date'], + ['type' => 'json', 'validation' => 'json', 'cast' => 'array'], ], ]; \ No newline at end of file diff --git a/src/Models/Attribute.php b/src/Models/Attribute.php index 1e43204..f52d885 100644 --- a/src/Models/Attribute.php +++ b/src/Models/Attribute.php @@ -53,8 +53,10 @@ public function setValueAttribute($value) { if(Config::get('attributes.validate_value_before_save')) { + $dataType = collect(Config::get('attributes.data_types'))->firstWhere('type', $this->data_type); + $validator = Validator::make(['value' => $value], [ - 'value' => $this->data_type + 'value' => $dataType['validation'] ]); if ($validator->fails()) {