laravel 使用布局模板的 Flash 消息重定向回来

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15815821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:40:14  来源:igfitidea点击:

Redirect back with flash message for the layout template

phpredirectlaravellaravel-4flash-message

提问by Matanya

In my controller I have a function to login a user.

在我的控制器中,我有一个登录用户的功能。

In case the login was successful I can simply use return Redirect::back().

如果登录成功,我可以简单地使用return Redirect::back().

My problem starts when the credentials are incorrect and I want to redirect with a flash message.

当凭据不正确并且我想使用 flash 消息重定向时,我的问题就开始了。

I know I can chain the withmethod to the Redirect, but that would send the data to the specific view, and NOT to the layout, where the login HTML lies.

我知道我可以将with方法链接到重定向,但这会将数据发送到特定视图,而不是发送到登录 HTML 所在的布局。

I could load a view like so:

我可以像这样加载视图:

$this->layout
     ->with('flash',$message)
     ->content = View::make('index');

But I need to redirect back to the referring page.

但我需要重定向回参考页面。

Is it possible to redirect while passing data to the layout?

在将数据传递到布局时是否可以重定向?

回答by Kylie

The Laravel Validator class handles this quite well.... The way I usually do it is to add a conditional within my layout/view in blade...

Laravel Validator 类很好地处理了这个问题......我通常这样做的方式是在我的布局/视图中添加条件...

{{ $errors->has('email') ? 'Invalid Email Address' : 'Condition is false. Can be left blank' }}

This will display a message if anything returns with an error.. Then in your validation process you have...

如果有任何返回错误,这将显示一条消息.. 然后在您的验证过程中,您有...

 $rules = array(check credentials and login here...);

$validation = Validator::make(Input::all(), $rules);

if ($validation->fails())
{
    return Redirect::to('login')->with_errors($validation);
}

This way...when you go to the login page, it will check for errors regardless of submission, and if it finds any, it displays your messages.

这样......当您进入登录页面时,无论提交如何,它都会检查错误,如果发现任何错误,它会显示您的消息。

EDITED SECTIONFor dealing with the Auth class.. This goes in your view...

编辑部分用于处理 Auth 类......这在你看来......

@if (Session::has('login_errors'))
    <span class="error">Username or password incorrect.</span>
@endif

Then in your auth...something along these lines..

然后在你的身份验证中......沿着这些方向的东西......

 $userdata = array(
    'username'      => Input::get('username'),
    'password'      => Input::get('password')
);
if ( Auth::attempt($userdata) )
{
    // we are now logged in, go to home
    return Redirect::to('home');
}
else
{
    // auth failure! lets go back to the login
    return Redirect::to('login')
        ->with('login_errors', true);

}