Passing javascript array to laravel controller in URL

631 0 0 0

Last Updated : 2024-04-20 09:41:08

this snippet will teach you how to pass javascript array from javascript to laravel controller in the url and how to get that array back in laravel controller

If you have a javascript array and want to pass it through the url to laravel controller you have to covert it to JSON first like this


$(document).on('click', "#exportBTN", function () {

amountsArrayJson = JSON.stringify(amountsArray); // create json array from your array - change amounts array to your array name
recordsArrayJson = JSON.stringify(SelectedRecordsArray); // create json array from your array - change amounts array to your array name
let exportURL = "{{route('admin.documents.export.csv')}}?
amountsArray="+amountsArrayJson+'&recordsArray='+recordsArrayJson+'&symbol='+add_item_symbol+'&docDate='+add_item_doc_date+'&docNumber='+add_item_doc_number; // pass it through the url like this
window.location.href = exportURL ;
});

and then you could get that array back in the controller function like this


public function adminExportCSV() {
$amounts = request()->get('amountsArray'); // change amounts array as the name in URL
$amountsArray = json_decode($amounts, true); // convert array back from json format
$records = request()->get('recordsArray');
$recordsArray = json_decode($records, true);
}

Mahmoud Anwar

Mahmoud Anwar

Back End Developer with a passion for developing innovative web applications that expedite the efficiency and effectiveness of organizational success. Well-versed in technology and writing code to create systems that are reliable and user-friendly. Also has the proven ability to motivate, educate, and collaborate effectively to build web applications and effectively track changes. Confident communicator, strategic thinker, and innovative creator to develop software that is customized to meet a company’s organizational needs, highlight their core competencies, and further their success.