加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – Laravel从私有方法重定向有错误

发布时间:2020-12-14 19:42:23 所属栏目:大数据 来源:网络整理
导读:我有以下代码: public function store(Request $request){ $this-validateData($request-all()); // store something return redirect()-action('controller@index')-withMessage( 'Saved Successfully' );}private function validateData($requestParams){
我有以下代码:

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' );
}

但我不希望这里有丑陋的if语句.必须有一种方法可以在没有闪存消息的情况下重定向.

解决方法

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();
    }
}

现在,看看Session驱动程序的save方法(ref)

public function save()
{
    $this->addBagDataToSession();
    $this->ageFlashData();
    $this->handler->write($this->getId(),$this->prepareForStorage(serialize($this->attributes)));
    $this->started = false;
}

如您所见,只有在Session中间件成功终止时才会保存您的Flash数据.使用旧代码,闪存数据将丢失!

我对我的代码所做的是在将响应发送到浏览器之前手动调用save方法.但是,我仍然建议您将重定向带到公共控制器方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读