You need to enable JavaScript to run this app. 如何在Laravel Blade中正确输出Session变量?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel Blade中正确输出Session变量?

问题根因
  • 你当前的代码混淆了两套完全独立的存储机制:
    • 你在JS中调用的sessionStorage.setItem()属于浏览器本地会话存储,数据仅保存在用户的浏览器本地,和Laravel运行在服务器端的Session没有任何数据关联。
    • Blade模板里的{{ Session::get('currency_code') }}是在服务端渲染页面、生成最终HTML的阶段执行取值操作,这个流程发生在浏览器收到页面内容之前,根本无法读取到页面加载完成后JS写入浏览器本地的存储内容,因此最终渲染结果为空。
解决方案

根据你的实际使用场景二选一即可:

场景1:需要将选中值存入Laravel服务端Session,后续支持服务端跨页面读取

  • 前端无法直接操作写入服务端Session,需要通过网络请求把选中值发送到后端,由后端完成Session写入:
    1. 调整Blade模板代码:
      @extends('ui.layout.app')
      
      @section('content')
       <div class="get-session">
          <select id="setSession" onchange="myFunction()">
            <option value="5">5</option>
            <option value="10">10</option>
          </select>
          <p id="get_session"></p>
          here : {{ Session::get('currency_code') }}
       </div>
      
       <script type="text/javascript">
          function myFunction() {
            const selectedValue = document.getElementById("setSession").value;
            // 替换原sessionStorage操作,向后端发送写入Session的请求
            fetch('{{ route('update.session.value') }}', {
              method: 'POST',
              headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({ currency_code: selectedValue })
            }).then(() => {
              // 写入完成后刷新页面,让Blade重新渲染读取最新的Session值
              window.location.reload();
            })
            document.getElementById("get_session").innerHTML = "You selected: " + selectedValue;
          }
        </script>  
      @endsection
      
    2. 在routes/web.php中配置对应后端接口:
      use Illuminate\Http\Request;
      
      Route::post('/update-session-value', function(Request $request) {
          // 校验传入参数
          $validated = $request->validate([
              'currency_code' => 'required'
          ]);
          // 将值写入Laravel服务端Session
          session()->put('currency_code', $validated['currency_code']);
          return response()->json(['success' => true]);
      })->name('update.session.value');
      

场景2:仅需在当前前端页面展示选中值,无需服务端读取

  • 无需使用Laravel的Session能力,直接通过浏览器本地存储实现即可,删除Blade中尝试读取服务端Session的冗余逻辑,改为前端JS读取本地存储内容同步更新DOM:
    @extends('ui.layout.app')
    
    @section('content')
     <div class="get-session">
        <select id="setSession" onchange="myFunction()">
          <option value="5">5</option>
          <option value="10">10</option>
        </select>
        <p id="get_session"></p>
        here : <span id="display-session-value"></span>
     </div>
    
     <script type="text/javascript">
        // 页面加载时读取本地存储的已有值并展示
        document.addEventListener('DOMContentLoaded', () => {
          const savedValue = sessionStorage.getItem('currency_code');
          if (savedValue) {
            document.getElementById('display-session-value').innerText = savedValue;
          }
        })
    
        function myFunction() {
          const selectedValue = document.getElementById("setSession").value;
          sessionStorage.setItem("currency_code", selectedValue);
          // 同步更新页面展示
          document.getElementById('display-session-value').innerText = selectedValue;
          document.getElementById("get_session").innerHTML = "You selected: " + selectedValue;
        }
      </script>  
    @endsection
    

内容的提问来源于stack exchange,提问作者Shishir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.05 02:45:07