[英]Laravel 5 How to perform validation in Controller to check for specific data in data collection
我想在laravel 5中執行自定義驗證,這是概念。 我有一個類別控制器,我想在其中刪除特定類別。 如果類別包含任何其他子類別,我想在laravel 5中顯示驗證錯誤。為此,我創建了程序,但是該程序未執行所需的驗證。 我遇到各種各樣的錯誤,例如找不到變量或驗證未執行或未定義變量:結構。 以下是我用來執行此操作的代碼。
CategroyController destroy function, to delete record.
public function destroy(Request $request)
{
if(\Request::ajax()){
$validator = \Validator::make($request->all(), array());
$data = Configuration::findTreeParent($request->input('id'), 'Category');
$selected = $request->input('id');
foreach($data as $struct) {
$validator->after(function($validator) {
if ($selected == $struct->id) {
$validator->errors()->add('field', $request->input('configname').' cannot be assigned to its child category.');
}
});
}
if ($validator->fails()) {
return $validator->errors()->all();
} else{
return \Response::json(['response' => 200,'msg' => $validator->fails()]);
}
}
}
請調查此問題並為我提供幫助。
使用closure
,需要在使用變量之前將變量傳遞給它的scope
。 在您的情況下, $struct
在閉包范圍內不可用,您將傳遞給$validator->after()
。
因此,基本上,您必須將$struct
傳遞給閉包。
// you can remove this line. $selected = $request->input('id');
$validator->after(function($validator) use ($struct) {
if ($request->input('id') == $struct->id) {
$validator->errors()->add('field', $request->input('configname').' cannot be assigned to its child category.');
}
});
要返回驗證錯誤的JSON響應,請更新以下代碼。
if ($validator->fails()) {
return \Response::json($validator->errors()->all(), 422);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.