0

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?

Script47
  • 14,230
  • 4
  • 45
  • 66
enbermudas
  • 1,603
  • 4
  • 20
  • 42
  • 1
    The error seems rather clear, you can't pass an array to the function, rather, it has to be a string. – Script47 Jun 23 '18 at 19:29
  • But i'm using a foreach loop with an array. Laravel documentation on "Eloquent: Mutators" says the next things about array/json casting: "...adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model" So, technically, this: $post->loot->content should return an array with one (or more) object: {"Item":2} and my loop should print: $name = Item and $amount = 2. (Sorry for my bad english, not a native speaker). – enbermudas Jun 23 '18 at 19:35

1 Answers1

0

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.

koalaok
  • 5,075
  • 11
  • 47
  • 91
  • This one throws the next error: json_decode() expects parameter 1 to be string, array given – enbermudas Jun 23 '18 at 19:36
  • I'm using your answer with a change. Instead of using json_decode, i did this: $obj = (array)$json and it works just fine! Thanks ! – enbermudas Jun 23 '18 at 19:39