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

Laravel LiveWire新手求助:读取字符串属性'id'报错问题

问题描述

我正在学习Laravel LiveWire,尝试用模拟数据测试foreach循环,但渲染时出现报错,无法正常输出数组值。

视图文件(livewire.create-post.blade.php)

<div>

    @php

            $posts =  array(
                "id" => "bar",
                "name" => "foo",
            );

    @endphp

    <h1>Title: "{{$title}}" </h1>

    <div>
    @foreach ($posts as $post)
        <div wire:key="{{ $post->id }}"> 
            <!-- ... -->
        </div>
    @endforeach
    </div>
</div>

控制器文件(App\LiveWire\CreatePost.php)

<?php

namespace App\LiveWire;

use Livewire\Component;

class CreatePost extends Component
{
    // 2024-12-22 14:45
    // as per docs https://livewire.laravel.com/docs/components#setting-properties
    
    public $title = 'Post title... RAD Software Systems' ;

    public function render()
    {
       return view('livewire.create-post');

        // return view('livewire.create-post')->with([
        //     'author' => Auth::user()->name,
        // ]);
    }
}

错误原因
  1. 数组结构错误:你定义的$posts是一维关联数组,foreach遍历它时,$post会拿到单个值(比如"bar"、"foo"),而非带id属性的对象/数组,调用$post->id自然会报错。
  2. 不符合LiveWire数据流规范:LiveWire更推荐在组件类中管理数据,而非视图内用@php硬编码,这会让组件逻辑更清晰。

修正方案

方案一:临时调整视图内数组结构

如果只是快速测试,把$posts改成包含多个帖子的二维数组,并使用数组访问语法:

<div>
    @php
        $posts = [
            ["id" => "1", "name" => "First Post"],
            ["id" => "2", "name" => "Second Post"],
        ];
    @endphp

    <h1>Title: "{{$title}}" </h1>

    <div>
    @foreach ($posts as $post)
        <div wire:key="{{ $post['id'] }}"> 
            <p>帖子ID: {{ $post['id'] }},名称: {{ $post['name'] }}</p>
        </div>
    @endforeach
    </div>
</div>

方案二:遵循LiveWire规范,在组件类中定义数据

这是更标准的做法,将数据逻辑放在组件类中:

控制器文件修改

<?php

namespace App\LiveWire;

use Livewire\Component;

class CreatePost extends Component
{
    public $title = 'Post title... RAD Software Systems';
    // 定义公共属性存储帖子数据
    public $posts = [];

    public function mount()
    {
        // 在mount钩子中初始化模拟数据
        $this->posts = [
            ["id" => "1", "name" => "First Post"],
            ["id" => "2", "name" => "Second Post"],
        ];
        // 如果想用对象格式,可转换:
        // $this->posts = [
        //     (object) ["id" => "1", "name" => "First Post"],
        //     (object) ["id" => "2", "name" => "Second Post"],
        // ];
    }

    public function render()
    {
       return view('livewire.create-post');
    }
}

视图文件修改(移除@php代码块)

<div>
    <h1>Title: "{{$title}}" </h1>

    <div>
    @foreach ($posts as $post)
        <!-- 数组格式用$post['id'],对象格式用$post->id -->
        <div wire:key="{{ $post['id'] }}"> 
            <p>帖子ID: {{ $post['id'] }},名称: {{ $post['name'] }}</p>
        </div>
    @endforeach
    </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 11:12:15