如何在不使用 Session 的情况下使用 Laravel 重定向将数据发送到视图?

How to send data to the view using redirect with Laravel without using Session?

我想将数据从控制器发送到我的视图,而不使用会话来获取视图中的数据。

this question中,他们建议使用return redirect('home')->with(['data' => $value]);,但我认为我必须使用Session::get('data')

我知道可以用return view('myView')->with('data', 'value')解决,但是我想把URL改成www.myurl.com/home 导航到主页时我无法使用 view('myView')->with('data', 'value').

执行此操作

谢谢!

没有别的办法,你真的需要Session::get。然而,我们可以做一个解决方法,但它很麻烦。

// some controller function
return redirect('home')->with(['data' => $value]);

现在在您的 home 控制器函数中,执行以下操作:

SomeController@home
...
$data = [];

// if you need to pass other data to view, put it in data[]
// e.g., $data['username'] = Auth::user()->username;

if (Session::has('data')) {
    $data['data'] = Session::get('data');
}

return view('myView', compact($data));

在您看来,您可以检查是否设置了 data

<!-- myView.blade.php -->
<span>{{ isset($data) ? $data : '' }}</span>

对我来说,这与从视图访问 Session 完全一样,因为如果您这样做,这就是您的视图的样子。

<!-- myView.blade.php -->
<span>{{ Session::has('data') ? Session::get('data') : '' }}</span>

您还可以使用 session() 全局帮助程序而不是 Session 门面。