Ad

Make A Nested Array To Laravel Request

- 1 answer

I am trying to add to a nested array in a request from my view to controller. I have dynamically generated the form in my view like this:

My View:

My Form View

The request currently looks like this:

enter image description here

How can turn my request like this:

"akunbelanja_id" => array:3 [▼
    0 => "1" => array:3 [▼
        0 => "topi"
        1 => "pensil"
        2 => "baju"
    ]
    1 => "2" => array:2 [▼
        0 => "kertas"
        1 => "tinta"
    ]                         
    2 => "3" => array:1 [▼
        0 => "botol"
    ]
]

Is it possible? Do I need additional Javascript or JQuery? And if possible, how can I access each data object in my controller?

Ad

Answer

In view

<script type = "text/javascript" >
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content');
        }
    });

function sendData() {
    // Your nested JS array goes here
    var data =  [
       {
          "1" : {0 : "topi",1 : "pensil",2 : "baju"}
       },
       {
          "2" : {0 : "kertas",1 : "kertas"}
       },
       {
          "3" : {0 : "botol"}
       }
    ];
    $.ajax({
        url: '/test',
        type: 'POST',
        dataType: 'json',
        contentType: 'json',
        data: JSON.stringify(data),
        contentType: 'application/json; charset=utf-8',
    });
} 
</script>

In controller

function saveJson(Illuminate\Http\Request $request)
{
    $data = json_decode($request->getContent());
}
Ad
source: stackoverflow.com
Ad