1

JSON format is saved in MySql column like this:

[{"id":1},{"id":2},{"id":3,"children":[{"id":4},{"id":5}]}]

And I did this in Laravel Blade;

@php
  $json = $categories->column;
  $array= json_decode($json , true);
@endphp

@foreach ($array as $key => $value)
  <li>{{ $value["id"] }}</li>
@endphp

And I get a result like this;

  • 1
  • 2
  • 3
  • But I can't get children results. What should I do for it? Thanks for your help.

    1 Answer 1

    4

    Try this code, You should have another loop for children if exists.

    @php
      $json = $categories->column;
      $array= json_decode($json , true);
    @endphp
    
    @foreach ($array as $key => $value)
      <li>{{ $value["id"] }}</li>
    
        //another loop for children if exists
        @if (isset($value["children"]))
            @foreach ($value["children"] as $child_key => $child_value)
              <li class="childs">{{ $child_value["id"] }}</li>
            @endforeach
        @endif
    
    @endforeach
    

    Your output will be this.

    1

    2

    3

    4

    5

    Sign up to request clarification or add additional context in comments.

    2 Comments

    Thank you for your answer. I tried the code you wrote, but I got an error like "Undefined index: children". What should i do ?
    @acnci use isset($value["children"]) to check that data exist.I update my answer, If you got your answer please accept it , thanks

    Your Answer

    By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.