jsonlaravellaravel-8htmlspecialchars

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


I have a Laravel Results model that returns some data from a database to a blade view from a 'results' table.
One of the columns is called properties which is of a json datatype and it stores data similar to the following:

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

The index controller gets the results from the getResults() function which returns an array of values such as match_id, home_team_goals, away_team_goals & properties - the properties (which is of a json datatype in the MySQL database is looped through on the frontend & I do the json_decode directly in the blade template, however it gives me the following error.

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

Weirdly when I run the json_decode() on the same data in the controller before I pass this into the view it works fine and creates an object as expected. However for some reason when I attempt to run the json_decode directly inside the blade view it returns the Error Exception above.

What's wrong?

Controller logic

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

Using PHP 8.x & Laravel 8.x


Solution

  • In the Laravel blade {{}} is equal to echo so it accept string not an object. It uses htmlspecialchars internally for XSS protection against injection. So when you are trying to do {{ json_decode($result->properties) }}, it is throughing the error. Instead you can use @php ... @endphp directives.

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