2017-06-14 77 views
0

Laravel动作,我用这样的形式请求文件的工作: ProjectCreateRequest.php当表单验证生成错误

public function rules() 
    { 
    $project_name = $this->project_name; 
    $meta_activity = $this->meta_activity; 
    return [ 
     'project_name' => 'required|max:255|unique:projects', 
     'customer_name' => 'required|max:255', 
     'otl_project_code' => 'sometimes|max:255|unique:projects,otl_project_code,NULL,id,meta_activity,'.$meta_activity, 
     'estimated_start_date' => 'date', 
     'estimated_end_date' => 'date', 
     'LoE_onshore' => 'numeric', 
     'LoE_nearshore' => 'numeric', 
     'LoE_offshore' => 'numeric', 
     'LoE_contractor' => 'numeric', 
     'revenue' => 'numeric', 
     'win_ratio' => 'integer' 
    ]; 
    } 

还有就是otl_project_code是必须与meta_activity独特。

如果有人输入一对已存在的otl_project_codemeta_activity,它会返回到创建页面,并显示下面写入的错误。

我想获得,而不是在控制器中,我可以捕获这些信息,做一些关于数据库然后重定向到更新url。

因为我有一个表单验证请求文件的工作,一切都进入了我的控制器是这样的:

public function postFormCreate(ProjectCreateRequest $request) 

,我不知道怎么在我的控制器来执行一些动作捕捉这个特定错误与我提交的所有字段并不返回到创建页面。当然,这只有在我上面提到的具体错误时才会发生。

回答

1

覆盖在你的ProjectCreateRequest的FormRequest响应函数:

/** 
* Get the proper failed validation response for the request. 
* 
* @param array $errors 
* @return \Symfony\Component\HttpFoundation\Response 
*/ 
public function response(array $errors) 
{ 
    if ($this->expectsJson()) { 
     return new JsonResponse($errors, 422); 
    } 

    return $this->redirector->to($this->getRedirectUrl()) 
            ->withInput($this->except($this->dontFlash)) 
            ->withErrors($errors, $this->errorBag); 
} 

这是对FormRequest类公众的反应,所以你可以编写自己的逻辑来执行的数据库查询和重定向需要的地方。