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

Laravel中Blade模板foreach循环报错:Cannot access offset of type string on string

问题描述

在Blade模板(blade.php)中使用foreach循环时,出现错误提示:Cannot access offset of type string on string,每次使用foreach循环都会触发该错误。

相关代码

Post.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul>
    @foreach($datafromtestmodel as $rows)
        <li>
            <p>{{$rows['name']}}</p>
            <p>{{$rows['company']}}</p>
            
        </li>
    @endforeach
    </ul>
    
</body>
</html>

控制器方法

public function index()
{
    $testmodeldata = new testmodel;
    $datafromtestmodel = $testmodeldata->abc();
    return view('post', compact('datafromtestmodel'));
}

模型方法

public function abc(){
    $blabla = ['name' => 'abc', 'company' => 'abc company'];
    return $blabla;
}

路由

Route::get('post','PostController@index');
问题原因与解决办法

原因

模型的abc()方法返回的是单个关联数组,但foreach需要遍历的是包含多个数组的集合/数组。当用foreach遍历单个关联数组时,循环会把数组的键(如'name'、'company')当作$rows的值,此时$rows是字符串,再尝试访问$rows['name']就会触发类型错误。

解决办法

有两种方案可选:

方案1:修改模型返回数组的格式

让模型返回包含单个数据数组的外层数组,这样foreach可以正常遍历:

public function abc(){
    $blabla = [['name' => 'abc', 'company' => 'abc company']];
    return $blabla;
}

方案2:直接访问单个数据(无需foreach)

如果原本就只需要展示这一条数据,直接在模板中访问数组元素即可,不用循环:

<ul>
    <li>
        <p>{{$datafromtestmodel['name']}}</p>
        <p>{{$datafromtestmodel['company']}}</p>
    </li>
</ul>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:15:32