简体   繁体   English

Laravel 5 中不发送会话变量

[英]Session variable is not sent in Laravel 5

I have a Laravel Application, and something strange is happening related to the session variables.我有一个 Laravel 应用程序,发生了一些与会话变量相关的奇怪事情。 I have a method in a controller that checks some inputs and depending of some conditions it decides if continues or just return back (and right here where is my problem), when I make return redirect()->back() I want so send a variable that is a Json, so briefly I have this:我在控制器中有一个方法可以检查一些输入,并根据某些条件决定是继续还是返回(我的问题就在这里),当我return redirect()->back()我想要发送一个 Json 变量,所以简单地说我有这个:

$msg=json_encode([
     'status' => 'failed',
     'field'=>'mail'
 ]);
return redirect()->back()->with('msg',$msg);

So, it redirects very well, but then in the view I have:所以,它重定向得很好,但在视图中我有:

@if ( Session::has('msg') )
   //come stuffs
@endif

But it seems likes the msg variable is not passed.但似乎没有传递msg变量。 According to the Laravel documentation when one uses redirect back the variables are accesible trough Session根据 Laravel 文档,当使用redirect back ,变量可以通过Session

Its' working for me when I tested.当我测试时,它对我有用。 Maybe your session is not storing data.也许您的会话没有存储数据。 Please check whether your session is working or not.请检查您的会话是否有效。 My tested output我的测试输出

   @if ( Session::has('msg') )
       {{ session('msg') }}
    @endif 

在此处输入图片说明

I also encountered this problem on a project a while back with Laravel 5.2.不久前,我在 Laravel 5.2 的一个项目中也遇到了这个问题。 I don't know if it is a bug or whether it has been fixed but I ended up getting around it by not using redirect()->back() .我不知道这是错误还是已修复,但我最终通过不使用redirect()->back()解决了它。 I think it might be related to the browser's caching mechanism.我认为这可能与浏览器的缓存机制有关。 I would be interested if you end up finding the cause.如果您最终找到原因,我会很感兴趣。

I think you need to use $request->session()->put('key', 'value');我认为你需要使用$request->session()->put('key', 'value'); before you initiate the redirect在您启动重定向之前

read the documentation at HTTP Session阅读HTTP Session 中的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM