如何防止出现required_without_all
验证器中存在的两个参数,例如:
return [
'user' => 'required_without_all:customer,public',
'customer' => 'required_without_all:user,public',
'public' => 'required_without_all:user,customer',
];
如何防止用户从上面一起提交2个密钥,例如:
http://127.0.0.1:8000/app/groups-statistics?user=10&customer=10
这些是允许的请求:
http://127.0.0.1:8000/app/groups-statistics?user=10
http://127.0.0.1:8000/app/groups-statistics?customer=10
http://127.0.0.1:8000/app/groups-statistics?public=true
不允许:
http://127.0.0.1:8000/app/groups-statistics?pubilc=true&customer=10
http://127.0.0.1:8000/app/groups-statistics?user=10&customer=10
http://127.0.0.1:8000/app/groups-statistics?public=10&customer=10
您可以使用Validator扩展来制作自己的验证器:
在AppServiceProvider
中放入以下代码:(或在任何提供商中(
public function boot(){
Validator::extend('present_only_one_from', function ($attribute, $value, $params, $validator) {
// $params = [user,customer,public]
$data = array_keys(array_filter($validator->getData())); // or you can write request()->all()
// $data = [user,customer] or [user,customer,public] or [user] ...
$intersect = array_intersect($data, $params); // returns matches of received and in validation rules
// $intersect [user,customer] && [user,customer,public] => [user,customer] => invalid
// $intersect [user] && [user,customer,public] => [user] => ($intersect[0] !== $attribute) => valid
// $intersect [customer] && [user,customer,public] => [customer] => ($intersect[0] !== $attribute) => invalid
if (count($intersect) != 1 && $intersect[0] !== $attribute) return false;
return true;
});
}
自定义验证器Closure接收四个参数:正在验证的$属性的名称、属性的$值、传递给规则的$参数数组以及validator实例。
然后在任何控制器中,您都可以使用以下规则:
$validator = Validator::make($request->request->all(), [
'user' => 'present_only_one_from:user,customer,public',
'customer' => 'present_only_one_from:user,customer,public',
'public' => 'present_only_one_from:user,customer,public',
]);
希望这能帮助你
您不能使用Laravel验证器来处理URL查询字符串,您必须使用中间件。
<?php
namespace AppHttpMiddleware;
use Closure;
class ValidateQueryString
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($public = $request->query('public')) {
if ($customer = $request->query('customer')) {
//Here both exist, handle your logic error
}
}
return $next($request);
}
}