autoValidation = $validate; } protected static function bootValidatable() { static::saving(function (Model $model) { if (!isset($model->autoValidation) || (isset($model->autoValidation) && $model->autoValidation)) { $model->validate(); //todo:add default values to request. } }); if (collect(class_uses_recursive(static::class))->contains(SoftDeletes::class)) { static::restoring(function (Model $model) { $model->validationState = $model->autoValidation; $model->autoValidate(false); }); static::restored(function (Model $model) { $model->autoValidate($model->validationState); }); } } /** * Common Rules for prevent duplicate! * * @return array */ public abstract function rules(): array; public function validate($fields = [], $abort = true) { $modelDocument = app('modelDocument'); $rules = $this->rules(); $rules = array_merge($rules, $this->createValidations()); $rules = array_merge($rules, $this->createValidations('category_data')); $validator = Validator::make($this->toArray(), $rules); if ($abort && $validator->fails()) { throw new ValidationException($validator, new JsonResponse([ "message" => "The given data was invalid.", "errors" => $validator->errors()->getMessages() ], Response::HTTP_UNPROCESSABLE_ENTITY) ); } //todo:shite code $fields = json_decode($this->attributes['fields'] ?? ''); collect($modelDocument?->fields)->filter(fn($f) => !empty($f['info']['default'])) ->each(function ($field) use (&$fields) { $fields->{$field['name']} = $fields->{$field['name']} ?? $field['info']['default']; }); if ($this->attributes['fields'] ?? false){ $this->attributes['fields'] = json_encode($fields); } return $abort ? $this : true; } public function getLoads() { return []; } public function allowLoad() { $includes = request()->filled('include') ? explode(',', trim(request()->include, ',')) : []; $getLoad = $this->getLoads(); $allow_load = []; foreach ($includes as $include) { $include = trim($include); if (in_array($include, $getLoad, true)) { array_push($allow_load, $include); } else { abort(Response::HTTP_BAD_REQUEST, "Requested include $include are not allowed"); } } $this->load($allow_load); return $this; } }