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

Laravel Blade中输出日期字段报错:Undefined property: stdClass::$show

问题解决:Laravel Blade中日期字段显示报错Undefined property: stdClass::$show

错误原因

你代码里的$show->show-date写法存在语法问题:PHP会将该表达式解析为($show->show) - date,也就是先尝试访问$show->show属性(但你的字段实际是show-date,不存在show属性),再减去date,因此触发了Undefined property错误。另外,DB::select()返回的是stdClass对象,日期字段以字符串类型存储,直接调用format()方法也会报错。

解决步骤

  1. 正确访问带连字符的字段
    对于包含特殊字符(如连字符)的字段名,需用花括号包裹属性名来访问:

    $show->{'show-date'}
    
  2. 将字符串日期转为Carbon实例
    数据库返回的日期是字符串,要调用format()方法需先转成Carbon对象,可使用Carbon::parse()方法:

    {{ \Carbon\Carbon::parse($show->{'show-date'})->format('Y-m-d') }}
    

修改后的完整代码

<?php $shows = DB::select("SELECT * FROM shows"); ?>
<div class="max-w-2xl p-6 mx-auto ">
    
    @foreach ($shows as $show)
        <div class="mt-6 p-6 bg-sp_white text-dk_brown shadow-sm rounded-lg">
            
            {{ \Carbon\Carbon::parse($show->{'show-date'})->format('Y-m-d') }}
            {{ $show->venue }} <!-- string --> 
            {{ $show->description }} <!-- string -->
            
        </div>

    @endforeach
</div>

可选优化

如果需要频繁处理这类日期字段,建议创建对应的Eloquent模型,在模型里将show-date字段设置为日期类型,Laravel会自动将其转为Carbon对象,使用更便捷:

// app/Models/Show.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Show extends Model
{
    protected $table = 'shows';
    protected $casts = [
        'show-date' => 'datetime',
    ];
}

控制器中改用模型查询:

$shows = \App\Models\Show::all();

Blade视图中可直接写:

{{ $show->{'show-date'}->format('Y-m-d') }}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:40:38