Json encode method in laravel

Updated at 02-Aug-2021, By samar

Json encode method in laravel

In this session, we will try our hand at solving the "Json encode method in laravel".

You can use JSON encode method to convert object/array to JSON format.
  • Return response with json_encode method in laravel

    $user = App\Models\User::select('id', 'name', 'email')->get();
    return json_encode($user);
    

    You can simply use the json_encode method to send data in JSON format.

  • Display JSON format data in html using jQuery each method

    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script>
    var html = '<ul>';
        $.each(response, function( index, value ) {
          html += '<li>' + value.name +'</li>';
        });
    html += '</ul>';
    $('body').append(html);
    </script>
    

    You can display JSON format data in HTML page using jQuery $.each() method.

Back to code snippet queries related laravel