Laravel 5.1 使用变量重定向

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

Laravel 5.1 Redirect with variable

phplaravelvariablesredirectlaravel-5.1

提问by utdev

I am trying to redirect in Laravel like this:

我正在尝试像这样在 Laravel 中重定向:

in my controller:

在我的控制器中:

  $state = false;
  return redirect()->route('newPr')->with('errorMessageDuration', 'error', $state);

and in my view I try to get it like this:

在我看来,我试着像这样得到它:

<input id="PrId" type="text" value="{{ isset($state) ? $state : '' }}">

but somehow it does not work, it keeps being empty.

但不知何故它不起作用,它一直是空的。

I want it to be saved permanently.

我希望它被永久保存。

回答by rzb

Use withErrors()with an associative array instead, like so:

withErrors()与关联数组一起使用,如下所示:

return redirect()->route('newPr')->withErrors(compact('state'));

Then you can simply use the $errors variable in your view.

然后您可以简单地在您的视图中使用 $errors 变量。

From the docs:

文档

The $errors variable is always defined and can be safely used. The $errors variable will be an instance of Illuminate\Support\MessageBag. For more information on working with this object, check out its documentation.

$errors 变量总是被定义并且可以安全使用。$errors 变量将是 Illuminate\Support\MessageBag 的一个实例。有关使用此对象的更多信息,请查看其文档

回答by Brendan Van Der Meulen

Try using the session to display it,

尝试使用会话来显示它,

<input id="PrId" type="text" value="{{ isset(session($state)) ? $session($state) : '' }}">

回答by Repox

Use sessions.

使用会话。

$request->session()->flash('error', 'Some error message');
return redirect()->route('newPr');

And in the view:

在视图中:

@if (session('error'))
    The error is {{ session('error') }}
@endif

回答by z3r0ck

withmethod takes 2 parameters. The 1st one being the keyand 2nd one valueOr if the 1st parameter is an array its keywill be the keyand valuewill be the value.

with方法需要2个参数。第一个是key第二个value或者如果第一个参数是一个数组,它key将会是key并且value将会是value

So in your case you can do ->with('state', $state)Or ->with(compact('state'))

所以在你的情况下,你可以做->with('state', $state)Or->with(compact('state'))

withmethod will flush this value to the sessionso in order to retrieve the value you need to get it from sessionlike this session('state')

with方法将此值刷新到sessionso 以检索您需要从session这样获取它的值session('state')

You can pass any value in this manner.

您可以通过这种方式传递任何值。

回答by Panagiotis Koursaris

You can't send variable with redirect, but if you want try with session.

您不能通过重定向发送变量,但如果您想尝试使用会话。

Take a look at my old answer here: Trying to pass a variable to a view, but nothing is shown in the view - laravel

在这里查看我的旧答案:尝试将变量传递给视图,但视图中未显示任何内容-laravel