前言
本文主要给大家介绍了关于laravel学习之model validation使用的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。
在对database进行写操作前,需要对数据进行validation,如type-check 每一个 model column 的定义('type' 这个column必须是enum('card','loan')) ,这里使用model event来做。
在eventserviceprovider(或自定义一个validationserviceprovider)中写上:
public function boot()
{
/**
* inspired by @see illuminatefoundationprovidersformrequestserviceprovider::boot()
*
* note: saving event is always triggered before creating and updating events
*/
$this->app['events']->listen('eloquent.saving: *', function (string $event_name, array $data): void {
/** @var appextensionsilluminatedatabaseeloquentmodel $object */
$object = $data[0];
$object->validate();
});
}
'eloquent.saving: *'是表示listen所有model的saving,即任何一个model的写操作都会触发该事件。
然后写一个abstract model extends eloquentmodel:
// appextensionsilluminatedatabaseeloquentmodel
use illuminatedatabaseeloquentmodel as eloquentmodel;
use illuminatevalidationvalidationexception;
abstract class model extends eloquentmodel
{
public function validate():void
{
// 1. validate type rules (type-check)
$validator = $this->gettypevalidator();
if ($validator->fails()) {
throw new validationexception($validator);
}
// $validator = $this->getconstraintvalidator();
// 2. validate constraint rules (sanity-check)
}
protected function gettypevalidator()
{
return $this->getvalidationfactory()->make($this->attributes, static::column_type_rules);
}
protected function getvalidationfactory()
{
return app(factory::class);
}
protected function getconstraintvalidator()
{
// return $this->getvalidationfactory()->make($attributes, static::column_constraint_rules);
}
}
这样,在每一个继承abstract model的子类中,定义const column_type_rules就行,如:
class account extends model
{
public const column_type_rules = [
'id' => 'integer|between:0,4294967295',
'source' => 'nullable|in:schwab,orion,yodlee',
'type' => 'required|in:bank,card,loan',
];
}
在写操作时,提前对每一个 model 的 schema definition进行type-check,避免无效碰撞 database。这个feature的目的是从model schema去校验输入数据的字段定义是否合法。
另外一般除了type-check schema definition 外,还得根据业务需要进行逻辑校验sanity-check constraint rules,如当创建一个account时,输入inputs里的字段person_id不能是child未成年人,等等。这里业务不同,constraint rules不同,不做过多解释。这个feature的目的主要是从逻辑上校验输入数据的合法性。
ok,总之一般情况下,在写数据库前都需要做 model validation,避免无效hit db。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对硕编程的支持。
【说明】:
本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!