【问题标题】:Laravel 4 'with' data persistingLaravel 4 'with' 数据持久化
【发布时间】:2013-05-11 19:14:40
【问题描述】:

我正在使用 Laravel 4 的 App::error 类在整个应用程序中捕获 Sentry 异常,并使用 withErrors() 函数将数据传回模板。

简单路线:

routes.php

Route::post('/login...

...

$credentials = array(
    'email'    => Input::get('email'),
    'password' => Input::get('password') 
);

$user = Sentry::authenticate($credentials);

// Exception thrown...

然后捕获异常:

exceptions.php

App::error(function(Cartalyst\Sentry\Users\WrongPasswordException $e) {
    return Redirect::back()->withErrors(array('failed' => 'Email or password is incorrect'))->withInput();
});

在视图中:

/views/login/login.blade.php

@if ($errors->has('failed'))
    <strong>{{ $errors->first('failed') }}</strong>
@endif

问题是,当您在尝试登录失败后刷新页面时,这些错误仍然存​​在,因此您会看到两次。第二次刷新,他们已经清除了。输入也是如此(使用withInput() 传递)。

如果在路由中(而不是在App:error 中)发现错误,则一切正常。我应该使用App::error 方法手动清除存储的数据吗?

【问题讨论】:

    标签: php laravel laravel-4 exception-handling cartalyst-sentry


    【解决方案1】:

    我总是使用 Session::flash() 来显示错误。 Flash 将(针对一个请求)将数据设置(并自动取消设置)到您的会话中。所以你可以去像

    App::error(function(Cartalyst\Sentry\Users\WrongPasswordException $e) {
        Session::flash('error', 'Email or password is incorrect.');
        return Redirect::back()->withInput();
    });
    

    并在你的视野中捕捉到这一点:

    @if($message = Session::get('success'))
        <div class="alert-box success">
            {{ $message }}
        </div>
    @endif
    
    @if($message = Session::get('error'))
        <div class="alert-box alert">
            {{ $message }}
        </div>
    @endif
    

    在相关说明中,我建议遵循通常的 try-catch 符号,如下所示:

    try {
        // do things that might throw an Exception here...  
    
    } catch(Cartalyst\Sentry\Users\UserExistsException $e) {
        // catch the Exception...
    
        Session::flash('error', Lang::get('register.user_already_exists'));
        return Redirect::action('RegisterController@getIndex')->withInput();
    
    }
    

    ...因为您当前对App::error() 所做的操作可能比这更麻烦。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      相关资源
      最近更新 更多