【问题标题】:Laravel session data get cleared out after redirect to next pageLaravel 会话数据在重定向到下一页后被清除
【发布时间】:2017-01-14 03:04:10
【问题描述】:

使用 Laravel 5.2

我试图将会话数据存储在控制器中,然后如果验证成功,我想将用户重定向到下一页。当我执行 Redirct::to('nextpage') 时,会话数据会在我的下一页和控制器中丢失。

这是从 'domainSearch' 获取表单 post 值的控制器

class domainSearch extends Controller
{ 
    public function store(Request $request)
    {
        // validate the info, create rules for the inputs
        $rules = array(
            'domainSearch'    => 'required' // make sure the username field is not empty
        );

        // run the validation rules on the inputs from the form
        $validator = Validator::make(Input::all(), $rules);

        // if the validator fails, redirect back to the form
        if ($validator->fails()) {
            return Redirect::to('/')
                ->withErrors($validator) // send back all errors to the login form
                ->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
        }
            else {
                // validation not successful, send back to form
            $request->session()->put('domainname', $request->get('domainSearch'));
                return Redirect::to('/domainlist');

            }

        }
    }

这是我试图将会话数据传递给并获取的控制器。但它始终保持为空。

 class DomainList extends Controller
    {
        public function index(Request $request){

            var_dump($request->get('domainname'));
            return view('domainlist');
        }
    }

如果我用 return view('view') 将用户发送到下一页;会话数据在那里,但在使用重定向功能时被清除。

如何在不丢失会话数据和变量的情况下进行重定向?

【问题讨论】:

  • 您使用 $request->session()->put 但随后使用 $request->get 。您可能需要使用$request->session()->get
  • 优秀.. :) 非常感谢!

标签: php laravel redirect laravel-5 frameworks


【解决方案1】:

在您的索引中尝试var_dump($request->session()->get('domainname'));

顺便说一句,您还可以使用session() 全局函数来存储或检索您的会话数据。

Route::get('home', function () {
  // Retrieve a piece of data from the session...
  $value = session('key');

  // Store a piece of data in the session...
  session(['key' => 'value']);
});

【讨论】:

  • "$value = session('key')" 在 Laravel 5.4 中重定向到另一个函数或控制器时不起作用
【解决方案2】:

这是因为您尝试检索 GET 参数而不是 SESSION 变量。试试这个:

 class DomainList extends Controller
{
    public function index(Request $request){

        var_dump($request->session()->get('domainname'));
        return view('domainlist');
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-08
    • 2012-08-05
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2020-08-16
    • 1970-01-01
    相关资源
    最近更新 更多