在 Laravel 中重定向以查看但更改 URL

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

Redirect to view but change URL in Laravel

laravelredirectview

提问by Alexandru Antochi

I'm trying to redirect the user after the create wizardis complete back to the main page.

我试图在create wizard完成后将用户重定向回主页。

If I write in my controller return view('main')->with('key'=>'data'), all is fine, but the URL does not change to localhost:8080but it stays as 'localhost:8080/wizard/finish`.

如果我在我的控制器中写入return view('main')->with('key'=>'data'),一切都很好,但 URL 不会更改为localhost:8080但它保持为 'localhost:8080/wizard/finish`。

If I use redirect('/')->with(['message' => 'Done.'])it redirects to the main page, but because there is already a Route::get('/','Controller'), the controller is triggered and it returns my default main page with no message.

如果我使用redirect('/')->with(['message' => 'Done.'])它重定向到主页,但因为已经有一个Route::get('/','Controller'),控制器被触发并返回我的默认主页,没有消息。

 <div class="row">
            <div class="col-12">
                @if (isset($message))
                    <p align="center" style="color: red;"><strong>{{$message}}</strong></p>
                @endif
            </div>
        </div>

EDIT: With a breakpoint in the MainPageController(mapped to /), I see that this controller is triggered when there is a redirect to the /route. Thus, I lose the $message, as the MainPageControlleralso returns the same view, but with no message.

编辑:在MainPageController(映射到/)中有一个断点,我看到这个控制器在重定向到/路由时被触发。因此,我丢失了$message, 因为MainPageController也返回相同的视图,但没有消息。

回答by Vishal Varshney

Try this

尝试这个

 return redirect('/url')->with('var', 'value');

回答by Alexey Mezenin

When you're redirecting, Laravel uses the session to keep the message between requests.

当你重定向时,Laravel 使用会话来保存请求之间的消息。

return redirect('/')->with('message', 'Done.');

So, to display the message change this:

因此,要显示消息,请更改以下内容:

@if (isset($message))
    <p align="center" style="color: red;"><strong>{{$message}}</strong></p>
@endif

To this:

对此:

@if (session()->has('message'))
    <p align="center" style="color: red;"><strong>{{ session('message') }}</strong></p>
@endif