Laravel 5 重定向消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34562501/
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 12:56:56  来源:igfitidea点击:

Laravel 5 redirect with message

phplaravelredirectlaravel-5laravel-5.2

提问by ?amo

Can someone explain why the code below does not work when it redirects to another page?

有人可以解释为什么下面的代码在重定向到另一个页面时不起作用吗?

return redirect()->route('homepage')->with('message', 'I am so frustrated.');

The redirect works as expected, but the message does not appear.

重定向按预期工作,但未显示消息。

The view looks like:

视图看起来像:

@if ( session()->has('message') )
    <div class="alert alert-success alert-dismissable">{{ session()->get('message') }}</div>
@endif

When I change it to:

当我将其更改为:

return redirect()->route('contact')->with('message', 'I am so frustrated.');

, which is the same as redirect()->back(), everything works fine and the message is displayed. What is the difference between redirect back()and to()another view?

,这与redirect()->back() 相同,一切正常并显示消息。重定向back()to()其他视图有什么区别?

采纳答案by patricus

If you're on Laravel 5.2, make sure all the routes you're using that access session data are contained in the webmiddleware group.

如果您使用的是 Laravel 5.2,请确保您使用该访问会话数据的所有路由都包含在web中间件组中。

If your contactroute is inside the webmiddleware group, but your homepageroute is not, that would explain your issue.

如果您的contact路线在web中间件组内,但您的homepage路线不在中间件组内,则可以解释您的问题。

回答by mangrove108

I am currently on Laravel 5.7 HTTP Redirectsand this code worked for me in the Controller:

我目前使用 Laravel 5.7 HTTP 重定向,这段代码在控制器中对我有用:

public function register(Request $request)
{
    $this->validator($request->all())->validate();
    event(new Registered($user = $this->create($request->all())));

    return $this->registered($request, $user) ?: 
    redirect($this->redirectPath())->with('success', 
    'An activation link was send to your email address.');
}

And in the View (etc.blade.php) i do:

在视图(etc.blade.php)中,我这样做:

@if(session('success'))
     <span class="alert alert-success" role="alert">
         <strong>{{ session('success') }}</strong>
     </span>
@endif