How to pass an array from view to controller? Using Laravel

Tags: , , , ,



I’m with an issue for some days that I can’t solve.

I should have a javascript/ajax/jQuery function in my View that creates an array and send the user to a new page using the Route “/modulos/contas_ti/gerar_protocolo”

Here is my javascript:

function check() {
    // I don't know how many numbers I will have in my array.
    // It will be dinamic. Can be [1, 2] or [1, 4, 5, 6] or anything else.
    var array = [1, 2];

    // I would like to pass 'array' in the URL below as parameter
    window.location.href = "{{URL::to('/modulos/contas_ti/gerar_protocolo')}}"
}

My Route:

// Maybe pass the array at the end of 'gerar_protocolo'? 
// Like 'gerar_protocolo[]=' ?

Route::get('/modulos/contas_ti/gerar_protocolo', 'ContasTIContasTIController@gerarProtocolo');

My Controller:

// How to pass the array as parameter inside ()? I also need to 
// pass the array to the new view using 'with', right? 
// Like with->('datas', $data);

public function gerarProtocolo() {
    return view('modulos.contas-ti.gerar_protocolo');
}

Answer

You can send it as a request parameter

function check() {
    var array = [1, 2];

    window.location.href = "{{URL::to('/modulos/contas_ti/gerar_protocolo')}}" + "?array[]=1&array[]=2";
}

Controller :

public function gerarProtocolo(Request $request) {
    $data = request('array');
    return view('modulos.contas-ti.gerar_protocolo', compact('data'));
}


Source: stackoverflow