Laravel 5.1 使用变量重定向

Laravel 5.1 Redirect with variable

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

在我的控制器中:

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

在我看来,我尝试这样实现:

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

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

我要永久保存。

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

看看我以前的回答:Trying to pass a variable to a view, but nothing is shown in the view - laravel

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

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

然后您只需在视图中使用 $errors 变量即可。

来自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.

尝试使用session来显示,

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

使用会话。

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

并且在视图中:

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

with 方法有两个参数。第一个是 key,第二个是 value 或者如果第一个参数是一个数组,它的 key 将是 keyvalue 将是 value.

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

with 方法会将这个值刷新到 session 所以为了检索你需要从 session 中获取它的值,就像这样 session('state')

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