这段代码几天前正在运作,但我似乎已经做了一些让它破裂的事情。
我有这条路线:
Route::post('admin/routemanagement', 'AdminController@addRoute');
看起来像这样:
public function addRoute(Request $request) {
if(Auth::check()) {
$rules = [
'flightDep' => 'required',
'flightArr' => 'required',
'flightDepTime' => 'required',
'flightArrTime' => 'required',
];
$messages = [
'flightDep.required' => 'A departure ICAO is required',
'flightArr.required' => 'An arrival ICAO is required',
'flightDepTime.required' => 'A departure time is required',
'flightArrTime.required' => 'An arrival time is required'
];
$validator = $this->validate($request, $rules, $messages);
if($validator->fails()) {
return redirect('admin/routemanagement')->withErrors($validator)->withInput();
}
}
但是,当此代码运行时,$validator
变量由于某种原因最终为null,我得到以下内容:
Call to a member function fails() on null
答案 0 :(得分:4)
来自Laravel文档:
“......如果验证失败,将自动生成正确的响应。如果验证通过,我们的控制器将继续正常执行。” (https://laravel.com/docs/5.2/validation)
因此,以下代码不是必需的:
if($validator->fails()) {
return redirect('admin/routemanagement')->withErrors($validator)->withInput();
}
如果验证失败,Laravel会自动响应,如果成功,则其余代码会正常执行。
答案 1 :(得分:0)
代替此默认验证
$validator = $this->validate($request, $rules, $messages);
您可以使用自定义验证
$validator = Validator::make($request->all(), [ // <---
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);