Howard
Howard

Reputation: 3758

Correct way to loop JSON contents using Laravel blade templating?

After passing in a JSON string like the following to the View. When I do...

<p>{{ $sets }}</p>

I get...

[{"name":"A"},{"name":"B"}, ... ,{"name":"Z"}]

However, when I try...

@foreach ($sets as $set)
    <p>{{ $set->name }}</p>
@endforeach

I'm getting the error, "Invalid argument supplied for foreach()".

I'm pretty sure this is an easy question though I'm not sure what's wrong.

Upvotes: 2

Views: 3452

Answers (1)

Eduardo Cruz
Eduardo Cruz

Reputation: 617

Are you using Json_Decode to create the $sets variable?

Try something like this to make sure there is no parsing error, happening:

    $sets = json_decode($data);

    switch (json_last_error()) {

        case JSON_ERROR_DEPTH:
            $json_error = 'Maximum stack depth exceeded';
            break;
        case JSON_ERROR_STATE_MISMATCH:
            $json_error =  'Underflow or the modes mismatch';
            break;
        case JSON_ERROR_CTRL_CHAR:
            $json_error =  'Unexpected control character found';
            break;
        case JSON_ERROR_SYNTAX:
            $json_error =  'Syntax error, malformed JSON';
            break;
        case JSON_ERROR_UTF8:
            $json_error =  'Malformed UTF-8 characters, possibly incorrectly encoded';
            break;
    }

After that, try adding a Var_dump($set) to see if each item is an object or an array. The way you are describing will only work if it is an object.

 @foreach ($sets as $set)
   <?php var)dump($set); ?>
 @endforeach

Upvotes: 1

Related Questions