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

Laravel中如何获取表行值并根据自定义订单状态设置行样式?

解决" Trying to get property 'option1' of non-object"错误并实现行样式切换

这个错误的根源很清晰:你把custom_order_status字段当成了关联对象来访问option1属性,但实际上它就是一个存储下拉框选项值的普通字段(比如字符串、数字),不是对象,所以才会抛出这个错误。

下面给你一步步的解决方案:

1. 先明确字段存储的实际值

首先要确认数据库里custom_order_status字段,当选中option1时存储的具体值是什么——可能是字符串'option1',也可能是数字1,或者是其他自定义标识,这个要和你下拉框选项的value对应上。

2. 修改视图中的判断逻辑

直接比较字段的实际值,而不是当成对象属性访问:

基础写法(假设存储值是'option1')

@foreach($dataTypeContent as $data)
    <tr class="{{ $data->custom_order_status === 'option1' ? 'alert alert-danger' : '' }}">
        <!-- 你的表格单元格内容 -->
    </tr>
@endforeach

更健壮的写法(处理字段为空的情况)

如果存在字段值为空的情况,加上空值判断可以避免潜在的报错:

@foreach($dataTypeContent as $data)
    <tr class="{{ !empty($data->custom_order_status) && $data->custom_order_status === 'option1' ? 'alert alert-danger' : '' }}">
        <!-- 你的表格单元格内容 -->
    </tr>
@endforeach

进阶写法(用模型常量维护,更易维护)

为了避免硬编码字符串,建议在对应的模型中定义常量,比如:

// 假设你的模型是App\Models\CustomOrder.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CustomOrder extends Model
{
    const STATUS_OPTION1 = 'option1';
    // 可以继续定义其他选项的常量:const STATUS_OPTION2 = 'option2';
}

然后在视图中引用常量:

@foreach($dataTypeContent as $data)
    <tr class="{{ $data->custom_order_status === \App\Models\CustomOrder::STATUS_OPTION1 ? 'alert alert-danger' : '' }}">
        <!-- 你的表格单元格内容 -->
    </tr>
@endforeach

3. 额外检查:字段名拼写是否一致

注意你问题描述里写的是custom_orders_status(复数orders),但代码里用的是custom_order_status(单数order),一定要确保字段名和数据库中的完全一致,这也是常见的排查点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:17:21