Laravel8.X对包含特定字符串的属性进行验证



我正在尝试制作一个应用程序,用于保存杂货清单并从数据库中检索它们。在请求中,值以JSON格式传递:

"item:47" => "{"id":47,"name":"Beer","brand":"Jupiler","weight":null,"note":"Six pack;_bottles","order_id":15}"
"item:88" => "{"id":88,"name":"Tomatoes","brand":null,"weight":null,"note":null,"order_id":15}"
"item:110" => "{"id":110,"name":"Gura_Bread","brand":null,"weight":0.3,"note":null,"order_id":15}"
"item:-1" => "{"id":-1,"name":"Beef_Jerky","brand":"Canadon","weight":0.5,"notes":"Spicy_Ones"}"

新项目用递减的负id标记,而现有项目则保留DB中的id

当它到达laravel应用程序的后端时,我想用laravel的validate()验证JSON字符串。唯一的问题是可以传递的项目数量在数量上有所不同。有时它可以是一个项目,而其他时候它可以是10个项目。

有没有一种方法可以添加这个JSON规则,它只能在注意到传入请求的一个或多个属性中有特定字符串时触发?在这种情况下,它应该在看到字符串item:时触发。

对于上下文,以下是示例请求的参数。

"picking_method" => "Cheapest"
"item:47" => "{"id":47,"name":"Beer","brand":"Jupiler","weight":null,"note":"Six pack;_bottles","order_id":15}"
"item:88" => "{"id":88,"name":"Tomatoes","brand":null,"weight":null,"note":null,"order_id":15}"
"item:110" => "{"id":110,"name":"Gura_Bread","brand":null,"weight":0.3,"note":null,"order_id":15}"
"item:-1" => "{"id":-1,"name":"Beef_Jerky","brand":"Canadon","weight":0.5,"notes":"Spicy_Ones"}"
"store_street" => "Haag Pines"
"store_number" => "1855"
"store_postal_code" => "82792-01"
"store_city" => "Port Muhammadhaven"
"store_country" => "Guernsey"
"delivery_street" => "Rosenbaum Island" 
"delivery_number" => "4974"
"delivery_postal_code" => "61093"
"delivery_city" => "East Carlee"
"delivery_country" => "Slovenia"
"delivery_notes" => null
"medical_notes" => null

经过更多的实验,我提出了这个解决方案

为了使此方法工作,您需要在要检查的所有属性中都有一个相同的子字符串。

在执行任何验证之前,我决定使用foreach循环将要检查的所有属性收集到一个数组中。这就是子字符串部分的重要之处,因为它将用于决定将收集哪些属性:

$item_attributes = [];
foreach ($request->post() as $key => $value) {
if (str_contains($key, 'item:')) {
array_push($item_attributes, $key);
}
}

之后,我在$item_attributes数组上循环,并使用它来创建一个规则数组,其中$item_attributes中的每个值都用作键。作为值,我添加了json规则。

$rules = [];
foreach ($item_attributes as $attribute) {
$rules[$attribute] = "json";
}

之后,我验证数据并返回,这样它就可以用于我的代码的主要功能:

return $request->validate($rules);

当组合时,这将导致以下方法:

function validateItems(Request $request)
{
$item_attributes = [];
foreach ($request->post() as $key => $value) {
if (str_contains($key, 'item:')) {
array_push($item_attributes, $key);
}
}
$rules = [];
foreach ($item_attributes as $attribute) {
$rules[$attribute] = "json";
}
return $request->validate($rules);
}

相关内容

  • 没有找到相关文章

最新更新