我从两个地方调用控制器方法store。首先,直接从表单提交开始,这意味着一旦我提交了from store方法就会被调用。
第二种方法是调用store方法,从其他方法的laravel。这是store方法代码。
public function store(MedicalAidRequest $request)
{
    //
    if(Auth::check()){
        $medicalAidRequest = session('medical_aid_request', $request->all());
        $medicalAidRequest['user_id'] = Auth::id();
        return $this->aidRepository->add($medicalAidRequest);
    }else{
        session(['medical_aid_request' => $request->all()]);
        return redirect('login')->with('from', 'aid_request');
    }
}我之所以使用这段代码,是因为我希望达到以下要求。
store方法从会话检索表单数据并保存到数据库中。但是,当我在日志记录之后在内部调用store方法时,由于store参数中的MedicalAidRequest在调用store方法之前验证来自表单请求的数据而导致验证失败。那我怎么才能做到这一点?
发布于 2019-04-04 17:15:20
第一:
在内部,您可以使用有效数据创建一个请求,然后在调用时传递给store方法。
您可以如下所示创建请求:
$request = new  <Namespace>\MedicalAidRequest();
然后,您可以使用替换方法手动添加输入,如下所示:
$request->replace(['key' => 'value']);
$controller = new YourController();
$controller->store($request);二次
您可以在控制器中而不是在表单请求中验证请求。如果这样做,您可以在存储方法中传递一个标志--例如$isInternal,如果是内部的是true,那么就不要运行验证。以下是如何:
public function store($isInternal = false)
{
  if(!$isInternal){
    $this->validate(request(), $this->rules());
  }
  //Rest of the code remain same
}
private function rules():array
{
  //return your rules array here as in the MedicalAidRequest
}发布于 2019-04-04 17:54:41
我在将内部调用转发给另一个控制器时遇到了同样的问题。
要解决这个问题,您必须创建一个具有所有所需参数的新请求对象,然后让应用程序内核处理它。通过这种方式,Laravel将处理精心编制的请求,就像在浏览器中一样。
要执行上述操作,请创建请求并调用app实例上的handle方法:
$request = Request::create($url, $action, $params, $cookies, $files, $headers);
$response = app()->handle($request);
// If needed you can use the response of the internal call
// if ($response->getStatusCode() == 404) {
//     abort(404);
// }如果您需要在多个地方使用该功能,您可以决定将其提取到它自己的特性(最快的方式);或者将逻辑移动到它自己的类中,以便在应用程序容器中绑定。
后一种方法允许只在需要时通过Laravel的输入从方法的签名中插入,或者通过app()实例手动解析依赖项。
如果您需要进一步解释类的提取/绑定,请告诉我,我将详细说明我的答案。
https://stackoverflow.com/questions/55521333
复制相似问题