承接 mamadali/laravel-validation-models 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

mamadali/laravel-validation-models

Composer 安装命令:

composer require mamadali/laravel-validation-models

包简介

Helps you easily validate your models and eloquent models with specific scenarios and use them in api

README 文档

README

Helps you easily validate your models and eloquent models with specific scenarios and use them in api

Latest Stable Version Total Downloads

Installation

The preferred way to install this extension is through composer.

Either run

composer require mamadali/laravel-validation-models "*"

or add

"mamadali/laravel-validation-models": "*"

to the "require" section of your composer.json file.

Basic Usage

First use trait in your model or eloquent model

in your form use like this

class Form
{
    use ModelValidationTrait;

in your eloquent models use like this

class User extends Model
{
    use EloquentModelValidationTrait;

then write your validation rules in validateRules() function in your model

    public function validateRules(): array
    {
        return [
            'title' => ['required', "string"],
            'number' => ['required', 'integer'],
        ];
    }

and you can load data received from end user to your model and validate data
->validate() function return true or false

Route::post('/test', function (Request $request) {
    // you can pass data from Request or array from user data to newModel function 
    $model = Form::newModel($request);
    $validate = $model->validate();

    // if $validate false $model->hasErrors() return false
    $hasErrors = $model->hasErrors();

    // you can get all error message as array with $model->getErrorMessages()
    $errors = $model->getErrorMessages();

    // you can get first error as string with $model->getFirstError()
    $firstErrorMessage = $model->getFirstError();

in eloquent models you can just call $model->save()

Route::post('/create-user', function (Request $request) {
    // you can pass data from Request or array from user data to newModel function 
    $model = User::newModel($request);

    $model->save();

in save function call validate function by default
if you need not call validate function

    $model->save(['validate' => false]);

Advanced Usage

Multiple Models

you can new multiple model from your request data if your data list of models

    $models = Form::newMultipleModel($request);
    // $models array from your form model with data received in request

Inline Validation

you can write your custom validation in your model
write function name as validate{Attribute}() in your model

    // your model
    
    public string $title;

    // validate rules
    .......

     /**
     * @param string $attribute in this example 'title'
     * @param mixed $value value of your attribute
     * @param array $options options passed in validate function
     * @param string $scenario model scenario
     */
    public function validateTitle($attribute, $value, $options, $scenario)
    {
        // your custom validation here
        // and you can add error to the model like this
        $this->addError($attribute, 'error message');
    }

Scenarios

you can set multi scenarios for your model like this

    public function scenarios() : array
        [
          'scenario1' => ['attribute11', 'attribute12', ...],
          'scenario2' => ['attribute21', 'attribute22', ...],
          ......
        ]
    }

and you can pass scenario when create your model

    $model = Form::newModel($request, 'scenario1');
    $models = Form::newMultipleModel($request, 'scenario2');

also you can set scenario on your model manually

    $model = new Form();
    $model->setScenario('scenario1');
    $model->loadModel($request);

when load attributes in your model only attributes in scenario set to your model

and you can get scenario currently your model on this

    $model->getScenario();

you can handle your validation rules with scenarios like this

    public function validateRules(): array
    {
        return [
            'title' => Rule::when($this->getScenario() == 'scenario1', ['required', 'string']),
            'number' => Rule::when($this->getScenario() == 'scenario2', ['required', 'integer']),
        ];
    }

Api Response

you can return your model data as response in your api
in your api controller

    return $model->responseAsJson();

in this order if your model has errors your response status code set to 422 and your error message in body
else return your model attributes with value in body

in some api if you need No Content with 204 status code response you can use this function

    return $model->responseNoContent();

you can customize your fields in api response with overwrite fields() function in your model like this

    public function fields(): array
    {
        // list of fields in response
        return [
            // field id cast to integer
            'id:int',
            // field title cast to string
            'title:string',
            // you can use your database relation like this (return relation model. you can custom fields in relation model)
            'dbRelation',
            // you can use specific field from your db relation
            'dbRelation.price',
            // and you can write custom field like this
            'custom:float' => function (self $model) {
                return $this->custom();
            },
        ];
    }

now supported cast type: int, string, float, bool

Get fields in api

you can write extra fields in your model like this

    public function extraFields(): array
    {
        // list of fields in response
        return [
            'extraTitle',
            ....
        ];
    }

extra fields are not included in the api response by default
and to get extra fields in the api response you need to add 'expand' parameter to your query params in request

in fields and extraFields method you can return recursively you model fields

http://127.0.0.1/api/test?expand=extraField1,extraField2
in this request get all fields in fields() function and fields defined in 'expand' parameter

and you can get specific fields in your response by add 'fields' parameter in query params

http://127.0.0.1/api/test?fields=id,title&expand=extraField1
in this request only get id,title and extraField1

Events

beforeValidate method is invoked before validation starts.
You may override this method in your model
If false is returned, the validation will stop and the model is considered invalid.

    public function beforeValidate() : bool
    {
        ... your code here ...
        return true;
    }

afterValidate method is invoked after validation ends.
You may override this method in your model

    public function afterValidate(): void
    {
        .... your code here ....
    }

beforeSave method is called at the beginning of inserting or updating a record in eloquent models. Override this method in your eloquent model
If false, the insertion or updating will be cancelled.

    public function beforeSave(array $options = []): bool
    {
        ... your code here ...
        return true;
    }

This method is called at the end of inserting or updating a record in eloquent models.
Override this method in your eloquent model:

    public function afterSave(array $options = []): void
    {
        ... your code here ...
    }

mamadali/laravel-validation-models 适用场景与选型建议

mamadali/laravel-validation-models 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 20 次下载、GitHub Stars 达 1, 最近一次更新时间为 2023 年 08 月 06 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 mamadali/laravel-validation-models 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 mamadali/laravel-validation-models 我们能提供哪些服务?
定制开发 / 二次开发

基于 mamadali/laravel-validation-models 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 20
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 9
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: Unknown
  • 更新时间: 2023-08-06