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

Laravel Blade遍历数组报错:无法访问字符串的偏移量

解决Blade模板foreach遍历数组时的"cannot access offset of type string on string"错误

问题描述

在Laravel项目的编辑页面Blade模板中,尝试通过foreach循环遍历$post->cage数组时,抛出错误:cannot access offset of type string on string。

相关代码片段

Blade模板代码

@foreach ($post->cage as $c)
    <div data-repeater-item="">
        <div class="form-group">
            <label class="col-sm-1 control-label">Make</label>
            <label class="col-sm-1 control-label">Comment</label>
            <div class="col-sm-2">
                <input type="text" name="cage[1][comment]" value="{{ $c['comment'] }}" class="form-control">
            </div>
        </div>
    </div>
@endforeach

控制器代码

/**
 * Show the form for editing the specified resource.
 */
public function edit(string $id): Response
{
    return response()->view('post.edit', [
        'post' => Posts::findOrFail($id),
    ]);
}

数据库与模型配置

  • 数据库迁移(cage为text字段):
/**
 * Run the migrations.
 */
public function up(): void
{
    Schema::table('posts', function (Blueprint $table) {
        $table->text('zone')->nullable();
        $table->text('cage')->nullable(); 
    });
}
  • 模型中的类型转换配置:
protected $casts = [
    'cage' => 'array'
];

数据结构(var_dump($post->cage)结果)

array(3) {   
    ["level"]=> string(6) "middle"
    ["comment"]=> string(4) "joe2"
    [0]=> array(2) {
        ["level"]=> string(6) "middle"
        ["comment"]=> string(4) "joe2" }
}

问题原因

尽管模型中配置了array类型转换,但text字段存储数组时,Laravel的类型转换对非标准结构的数组(同时包含关联键与数字索引)兼容性较差,无法确保将存储的字符串正确解析为可遍历的PHP数组,导致遍历时报错。

解决方法

将cage字段从text类型修改为json类型,Laravel对JSON字段的类型转换支持更完善,能稳定解析存储的数组结构。

修改字段类型(针对已存在的表)

创建新的迁移文件执行字段修改:

public function up(): void
{
    Schema::table('posts', function (Blueprint $table) {
        $table->json('cage')->nullable()->change();
    });
}

模型中的$casts配置保持不变,修改完成后即可正常通过foreach遍历$post->cage数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 07:27:39