Laravel 5.8: 请求会话似乎没有在控制器上设置会话

Laravel 5.8: Request session does not seem to setting the session at Controller

我的请求会话似乎没有在控制器中设置会话。正如您所说 $request->session()->flash('charge_wallet',$wallet); 所见,我尝试设置会话 charge_wallet.

然后在视图中,bankGateWay.getToken,我尝试检查会话是否存在。但它 returns 不存在 不知何故!那么这里出了什么问题?我该如何解决这个问题?

控制器

public function chargeWallet(Request $request, $wallet, $user)
{
    try {
        $data = $request->validate([
            'charge' => 'required|integer|min:1000',
        ]);

        $payment = Payment::create([
            'pay_type_id' => '191',
            'pay_date' => jdate()->format('Y/m/d'),
            'pay_amount' => $data['charge'] * 10,
            'pay_ord_id' => '',
            'pay_status_id' => '181',
            'pay_creator_id' => auth()->user()->usr_id,
        ]);

        $request->session()->flash('charge_wallet', $wallet); // Setting Session

        $sendInformation = new BankGateWay($payment->pay_id, 
            $payment->pay_amount, $payment->created_at->timestamp,
            route('returnFromGateCharge'));
        
        return view("bankGateWay.getToken", compact('sendInformation'));
    } catch (\Exception $e) {
        return redirect()->back()->with('error', 'Wrong Data');
    }
}

查看

@if(Session::has('charge_wallet'))
    @dd('exists');
@else
    @dd('not exists');
@endif
public function chargeWallet(Request $request, $wallet, $user)
    {
        try {
            $data = $request->validate([
                'charge' => 'required|integer|min:1000',
            ]);

            $payment = Payment::create([
                'pay_type_id' => '191',
                'pay_date' => jdate()->format('Y/m/d'),
                'pay_amount' => $data['charge'] * 10,
                'pay_ord_id' => '',
                'pay_status_id' => '181',
                'pay_creator_id' => auth()->user()->usr_id,
            ]);

            $sendInformation = new BankGateWay($payment->pay_id, $payment->pay_amount, $payment->created_at->timestamp, route('returnFromGateCharge'));
            return view("bankGateWay.getToken", compact('sendInformation'))->with('charge_wallet',$wallet);
        }catch (\Exception $e) {
            return redirect()->back()->with('error', 'Wrong Data');
        }
    }

实际上正如 Laravel documentation 所说,您可以将它用于下一个请求,例如在重定向之后。

Data stored in the session using this method will be available immediately and during the subsequent HTTP request. After the subsequent HTTP request, the flashed data will be deleted.

但是在你的代码中你想在你的视图中显示它,这被认为是在同一个请求中。对于当前请求,您应该使用 now 方法。

$request->session()->now('charge_wallet',$wallet');

如果要设置更长的时间,请使用put方法。

$request->session()->put('charge_wallet',$wallet');