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

前端之家收集整理的这篇文章主要介绍了php – Laravel从私有方法重定向有错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码

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方法.但是,我仍然建议您将重定向带到公共控制器方法.

猜你在找的Laravel相关文章