mamadali / laravel-validation-models
帮助您轻松验证模型和Eloquent模型,并使用特定场景在API中使用
Requires
- php: >=8.0
- illuminate/collections: >=8.0
- illuminate/http: >=8.0
This package is auto-updated.
Last update: 2024-09-15 21:35:44 UTC
README
帮助您轻松验证模型和Eloquent模型,并使用特定场景在API中使用
安装
安装此扩展的首选方式是通过 Composer。
运行
composer require mamadali/laravel-validation-models "*"
或在您的 composer.json
文件的 "require" 部分添加
"mamadali/laravel-validation-models": "*"
。
基本用法
在您的模型或Eloquent模型中首先使用特性
在您的表单中使用如下
class Form { use ModelValidationTrait;
在您的Eloquent模型中使用如下
class User extends Model { use EloquentModelValidationTrait;
然后在您的模型中编写 validateRules() 函数中的验证规则
public function validateRules(): array { return [ 'title' => ['required', "string"], 'number' => ['required', 'integer'], ]; }
并将从最终用户接收的数据加载到模型中,并验证数据
->validate() 函数返回 true 或 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();
在Eloquent模型中,您可以直接调用 $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();
在 save 函数中默认调用 validate 函数
如果您不需要调用 validate 函数
$model->save(['validate' => false]);
高级用法
多个模型
您可以从请求数据中创建多个模型
$models = Form::newMultipleModel($request); // $models array from your form model with data received in request
内联验证
您可以在模型中编写自定义验证
在模型中编写函数名为 validate{Attribute}() 的函数
// 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'); }
场景
您可以为模型设置多个场景,如下所示
public function scenarios() : array [ 'scenario1' => ['attribute11', 'attribute12', ...], 'scenario2' => ['attribute21', 'attribute22', ...], ...... ] }
并且您可以在创建模型时传递场景
$model = Form::newModel($request, 'scenario1'); $models = Form::newMultipleModel($request, 'scenario2');
也可以在模型上手动设置场景
$model = new Form(); $model->setScenario('scenario1'); $model->loadModel($request);
当在模型中加载属性时,只有设置到模型上的场景中的属性
并且您可以获取当前模型上的场景
$model->getScenario();
您可以使用场景处理验证规则,如下所示
public function validateRules(): array { return [ 'title' => Rule::when($this->getScenario() == 'scenario1', ['required', 'string']), 'number' => Rule::when($this->getScenario() == 'scenario2', ['required', 'integer']), ]; }
API响应
您可以将模型数据作为响应返回在API中
在您的API控制器中
return $model->responseAsJson();
如果模型有错误,则将响应状态码设置为422,并将错误消息放在正文
否则返回正文中的模型属性和值
在某些API中,如果您需要使用204状态码的 No Content 响应,您可以使用此函数
return $model->responseNoContent();
您可以通过在模型中覆盖 overwriteFields() 函数来自定义API响应中的字段,如下所示
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(); }, ]; }
现在支持的类型:int, string, float, bool
在API中获取字段
您可以在模型中编写额外的字段,如下所示
public function extraFields(): array { // list of fields in response return [ 'extraTitle', .... ]; }
默认情况下,额外字段不包括在API响应中
要获取API响应中的额外字段,您需要在请求的查询参数中添加 'expand' 参数
在 fields 和 extraFields 方法中,您可以递归地返回模型字段
http://127.0.0.1/api/test?expand=extraField1,extraField2
在此请求中,获取 fields() 函数中的所有字段和 'expand' 参数中定义的字段
并且您可以通过在查询参数中添加 'fields' 参数来获取响应中的特定字段
http://127.0.0.1/api/test?fields=id,title&expand=extraField1
在此请求中,仅获取 id, title 和 extraField1
事件
beforeValidate 方法在验证开始之前被调用。
您可以在模型中重写此方法
如果返回 false
,则验证将停止,模型被视为无效。
public function beforeValidate() : bool { ... your code here ... return true; }
afterValidate 方法在验证结束后被调用。
您可以在模型中重写此方法
public function afterValidate(): void { .... your code here .... }
在eloquent模型中插入或更新记录的开始阶段会调用beforeSave方法。在你的eloquent模型中重写此方法
如果设置为false
,则插入或更新操作将被取消。
public function beforeSave(array $options = []): bool { ... your code here ... return true; }
在eloquent模型中插入或更新记录结束时调用此方法。
在你的eloquent模型中重写此方法
public function afterSave(array $options = []): void { ... your code here ... }