json_decode () 在 Laravel Blade 模板中直接调用时中断 - (期望字符串,object 给定)

json_decode () breaking when called directly in the Laravel Blade template - (expects string, object given)

我有一个 Laravel Results 模型,其中 returns 一些数据从数据库到 blade 来自 'results' table 的视图.
其中一列称为 properties,属于 json 数据类型,它存储类似于以下内容的数据:

{
"clubs": [
    {
        "id": 1741008,
        "name": "BanterburyFC",
        "wins": "0"
    },
    {
        "id": 17844730,
        "name": "es ticazzi",
        "wins": "1"
    }
]
}

索引控制器从 getResults() 函数获取结果,该函数 returns 一个值数组,例如 match_id, home_team_goals, away_team_goals & properties - 属性(属于 json 数据类型MySQL 数据库在前端循环运行,我直接在 blade 模板中执行 json_decode,但是它给了我以下错误。

htmlspecialchars() expects parameter 1 to be string, object given (View: /Users/myname/Projects/myapp/resources/views/dashboard.blade.php)

奇怪的是,当我 运行 控制器中相同数据的 json_decode() 在我将其传递到视图之前它工作正常并按预期创建 object 。但是出于某种原因,当我尝试 运行 直接在 blade 中查看 returns json_decode 上面的错误异常时。

怎么了?

控制器逻辑

public function index()
{
    $user = auth()->user();
    $data = [ 'results' => Result::getResults($user->properties) ];

    // var_dumping so I can check the data before it is passed to the blade view
    var_dump($data['results'][0]->properties);  // returns string - looks fine & this doesn't return any errors
    var_dump(json_decode($data['results'][0]->properties)); // returns object - looks fine & this doesn't return any errors either
    return view('dashboard', $data);
} 

Blade view/template

@foreach ($results as $result)
    {{ json_decode($result->properties) }} <!-- the line causing the problem -->
    {{ json_decode($result->properties, true) }} <!-- this also fails -->
@endforeach

使用 PHP 8.x & Laravel 8.x

在 Laravel blade {{}} 中等于 echo 所以它接受字符串而不是 object。它在内部使用 htmlspecialchars 来防止 XSS 注入。因此,当您尝试执行 {{ json_decode($result->properties) }} 时,它正在通过错误。相反,您可以使用 @php ... @endphp 指令。

@foreach ($results as $result)
    @php $p = json_decode($result->properties); @endphp 
@endforeach