Laravel: How do I parse this json data in view blade?

后端 未结 8 1257
耶瑟儿~
耶瑟儿~ 2020-11-29 03:11

Currently this is my view

{{ $leads }}

And this is the output

{\"error\":false,\"member\":[{\"id\":\"1\",\"firstName\":\"fi         


        
相关标签:
8条回答
  • 2020-11-29 03:28

    Just Remove $ in to compact method ,
    return view('page',compact('member'))

    0 讨论(0)
  • 2020-11-29 03:30

    You can use json decode then you get php array,and use that value as your own way

    <?php 
    $leads = json_decode($leads, true);
    dd($leads);
    
    0 讨论(0)
  • 2020-11-29 03:32

    It's pretty easy. First of all send to the view decoded variable (see Laravel Views):

    view('your-view')->with('leads', json_decode($leads, true));
    

    Then just use common blade constructions (see Laravel Templating):

    @foreach($leads['member'] as $member)
        Member ID: {{ $member['id'] }}
        Firstname: {{ $member['firstName'] }}
        Lastname: {{ $member['lastName'] }}
        Phone: {{ $member['phoneNumber'] }}
    
        Owner ID: {{ $member['owner']['id'] }}
        Firstname: {{ $member['owner']['firstName'] }} 
        Lastname: {{ $member['owner']['lastName'] }}
    @endforeach
    
    0 讨论(0)
  • 2020-11-29 03:35

    it seems you can use @json($leads) since laravel 5.5

    https://laravel.com/docs/5.5/blade

    0 讨论(0)
  • 2020-11-29 03:35

    The catch all for me is taking an object, encoding it, and then passing the string into a javascript script tag. To do this you have to do some replacements.

    First replace every \ with a double slash \\ and then every quote" with a \".

    $payload = json_encode($payload);
    $payload = preg_replace("_\\\_", "\\\\\\", $payload);
    $payload = preg_replace("/\"/", "\\\"", $payload);
    return View::make('pages.javascript')
      ->with('payload', $payload)
    

    Then in the blade template

    @if(isset($payload))
    <script>
      window.__payload = JSON.parse("{!!$payload!!}");
    </script>
    @endif
    

    This basically allows you to take an object on the php side, and then have an object on the javascript side.

    0 讨论(0)
  • 2020-11-29 03:36

    in controller just convert json data to object using json_decode php function like this

    $member = json_decode($json_string); 
    
    and pass to view in view
    
    return view('page',compact('$member'))
    

    in view blade

    Member ID: {{$member->member[0]->id}}
    Firstname: {{$member->member[0]->firstname}}
    Lastname: {{$member->member[0]->lastname}}
    Phone: {{$member->member[0]->phone}}
    
    Owner ID: {{$member->owner[0]->id}}
    Firstname: {{$member->owner[0]->firstname}}
    Lastname: {{$member->owner[0]->lastname}}
    
    0 讨论(0)
提交回复
热议问题