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

如何在Laravel Blade中校验jQuery生成的逗号分隔Cookie与后端变量匹配

Laravel Blade校验前端jQuery生成Cookie的实现方案

背景说明

  • 前端通过jQuery创建名为DeliveryToken的Cookie,用户输入的多个值用逗号拼接存在同一个Cookie中
  • 后端Laravel需要校验Cookie中是否包含指定用户标识,匹配才展示页面内容,否则提示无效

前端jQuery创建Cookie代码

<script type="text/javascript">
    $(function () {
        $("#btnAdd").click(function () {
            if($('#addtokendelivery').val() === ''){
                alert('Valor en Blanco');       
            } else {
                if ($.cookie('DeliveryToken')) {
                    $.cookie("DeliveryToken", $.cookie("DeliveryToken") + ',' + $("#addtokendelivery").val());
                    alert('Repartidores Agregados con Token´s: ' + $.cookie("DeliveryToken"));                  
                } else{
                    $.cookie("DeliveryToken", $("#addtokendelivery").val());
                    alert('Repartidor Agregado con Token: ' + $.cookie("DeliveryToken"));               
                }       
            }   
        });
        $("#btnRead").click(function () {
            alert($.cookie("DeliveryToken"));
        });
    });
</script>

Cookie存储格式示例(谷歌浏览器)

DeliveryToken: value1,value2,value3

Laravel后端获取待匹配变量代码

$orderitemaddons32 = DB::table('users')->where('id', $id)->first();
$orderitemaddons32 = $orderitemaddons32->userdelivery_id;
// 变量输出结果示例:"value1"

Blade模板校验实现

直接在Blade模板中加入如下判断逻辑即可:

@php
// 获取前端存储的Cookie
$deliveryTokenCookie = request()->cookie('DeliveryToken');
// 将Cookie值按逗号拆分为数组,为空则赋值为空数组避免报错
$tokenArr = empty($deliveryTokenCookie) ? [] : explode(',', $deliveryTokenCookie);
@endphp

@if(in_array($orderitemaddons32, $tokenArr))
    {{-- 校验通过,此处放正常展示的页面内容 --}}
    <div>
        页面正常内容
    </div>
@else
    {{-- 校验不通过,展示错误提示 --}}
    <div style="text-align: center; margin-top: 100px;">
        <h3>信息无效,无法访问当前页面</h3>
    </div>
@endif

注意:如果你的Cookie是加密存储的(Laravel默认对Cookie加密),需要先在app/Http/Middleware/EncryptCookies.php中将DeliveryToken加入排除加密的数组,否则无法直接读取到明文值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 11:45:08