htmlspecialchars expects parameter 1 to be string, array given

I am getting the next error while printing a model content on my blade.php view:

htmlspecialchars() expects parameter 1 to be string, array given

This model “content” is a column (json type) in a table and it looks just like this:
[{"Item":2}]

And this is how i’m trying to use it on my view:
@foreach ($post->loot->content as $name => $amount)
     <div class="item">
          <i class="fab fa-cuttlefish"></i>
          <div class="text">{{ $name }} <b>x{{ $amount }}</b></div>
     </div>
@endforeach

For some reason, if i print $name alone, it shows the number (2) that should be printed while using the $amount variable.

Is there any way to solve my problem?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If $post->loot->content contains [{“Item”:2}]

It is an array of objects so, your $amount is the whole {“Item”:2}, not 2.

so the loop can be something like:

@foreach ($post->loot->content as $id=>$json)
    @php
        $obj =json_decode($json, true)
    @endphp
    @foreach ($obj as $key=>$val)
     <div class="item">
          <i class="fab fa-cuttlefish"></i>
          <div class="text">{{ $key }} <b>x{{ $val }}</b></div>
     </div>
     @endforeach
@endforeach

Not sure what you need but maybe you can swap
 <div class="text">{{ $key }} <b>x{{ $val }}</b></div>

with
   <div class="text">{{ $id }} <b>x{{ $val }}</b></div>

If you need the index of the whole object in the list instead of the attribute’s obj key.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x