我有以下代码:
public function store(Request $request) { $this->validateData($request->all()); // store something return redirect()->action('controller@index')->withMessage( 'Saved Successfully' ); } private function validateData($requestParams) { try { $validator->validate( $requestParams ); } catch ( ValidationException $e ) { redirect()->action('controller@create')->withInput()->withErrors( $e->get_errors() )->send(); exit(); // this causes the withErrors to not be there } }
如果我删除exit();,将出现错误消息,但也将执行存储函数(请参阅//存储某些内容).我知道我可以重写我的代码:
if($this->validateData($request->all())) { // store something return redirect()->action('controller@index')->withMessage( 'Saved Successfully' ); }
解决方法
TL;博士
像这样更新你的私有方法代码,使重定向工作与$errors变量可见:
private function validateData($requestParams) { try { $validator->validate( $requestParams ); } catch ( ValidationException $e ) { $resp = redirect()->action('WelcomeController@index')->withInput()->withErrors($e->get_errors()); \Session::driver()->save(); $resp->send(); exit(); } }
交代
当退出控制器中间时,在应用程序终止中执行的某些作业将不再执行.在您的情况下,将不会调用会话中间件终止方法.让我们看看它的内容(ref):
public function terminate($request,$response) { if ($this->sessionHandled && $this->sessionConfigured() && ! $this->usingCookieSessions()) { $this->manager->driver()->save(); } }
public function save() { $this->addBagDataToSession(); $this->ageFlashData(); $this->handler->write($this->getId(),$this->prepareForStorage(serialize($this->attributes))); $this->started = false; }
如您所见,只有在Session中间件成功终止时才会保存您的Flash数据.使用旧代码,闪存数据将丢失!