You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel API中传递Session变量及Blade代码示例

在Laravel API中传递Session变量的方法

首先得明确:Laravel的API路由默认是不启用Session的,因为它默认是为无状态的API场景设计的。不过咱们可以通过调整中间件来开启Session支持,再结合你的Blade视图来实现数据传递,具体步骤如下:

1. 调整API中间件组,开启Session支持

打开项目根目录下的app/Http/Kernel.php文件,找到$middlewareGroups里的api数组,把Session相关的中间件加进去——因为Session依赖Cookie,所以需要同时添加Cookie加密、Cookie响应和Session启动这三个中间件:

protected $middlewareGroups = [
    'web' => [
        // ... web中间件原有内容
    ],

    'api' => [
        \Illuminate\Cookie\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

2. 在API控制器中设置Session变量

假设你有一个API接口用来处理产品数据,在对应的控制器方法里,把需要传递的数据存入Session:

use Illuminate\Http\Request;

public function storeProductSession(Request $request)
{
    // 这里假设$product1是你已经获取到的产品数据
    $request->session()->put('product_list', $product1['domains']['domain']);
    
    return response()->json(['status' => 'success', 'message' => '产品数据已存入Session']);
}

3. 在Blade视图中读取Session变量

你提供的Blade代码原本是遍历$product1变量,现在改成从Session中读取数据即可,用session()辅助函数就能轻松获取,还可以设置默认值避免Session为空时报错:

@foreach(session('product_list', []) as $product)
    <tr role="row">
        <td class="sorting_desc" tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1" aria-label="Rendering engine: activate to sort column ascending" aria-sort="descending">1</td>
        <td class="sorting" tabindex="0" aria-controls="DataTables_Table_0" rowspan="1" colspan="1" aria-label="Browser: activate to sort column ascending">
            <a href="" style="color:#23b7e5" data...>
                <!-- 这里补充你的链接内容 -->
            </a>
        </td>
        <!-- 其他表格单元格内容 -->
    </tr>
@endforeach

一些需要注意的点

  • 跨域问题:如果你的API和前端页面是跨域的,那还需要配置CORS允许携带凭证,同时前端请求要设置withCredentials: true(比如Axios请求里加上这个配置),否则Cookie无法正常传递,Session也就失效了。
  • API设计建议:其实Session更适合传统的服务端渲染场景,如果你是前后端分离的API架构,更推荐用Token认证(比如Passport或Sanctum),把需要传递的数据放在Token的Payload里,或者存在Redis/数据库中通过用户ID关联,这样更符合API无状态的设计原则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:03:57