简体   繁体   中英

Laravel - How to pass array of objects to controller

I'm currently doing a project for the company where I'm taking my internship and this one is a very important module for that said project. How could I pass array of objects to route or controller from ajax inside a javascript function and how to use the passed array of objects inside the target Controller?

This is the javascript function:

function AddInvoiceItemServ() { //add new item/service information
        var newInvoiceItemServArr = new Array;
        var grandTotal = 0;
        var date = new Date();
        var result = date.getFullYear() + '-' + ((date.getMonth().toString().length > 1) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '-' + ((date.getDate().toString().length > 1) ? date.getDate() : ('0' + date.getDate()));
        for(var index = 0; index < ($("#tblViewInvoiceItemServ").children("tbody").children("tr").length - 2); index++) {
            if($("#tblViewInvoiceItemServ").children("tbody").children("tr:eq(" + index + ")").is(":visible")) {
                newInvoiceItemServObj = new Object;
                newInvoiceItemServObj.description = $("#tblViewInvoiceItemServ").children("tbody").children("tr:eq(" + index + ")").children("td:eq(0)").html();
                newInvoiceItemServObj.unit_price = parseInt($("#tblViewInvoiceItemServ").children("tbody").children("tr:eq(" + index + ")").children("td:eq(1)").html().replace("₱", ""));
                newInvoiceItemServObj.quantity = parseInt($("#tblViewInvoiceItemServ").children("tbody").children("tr:eq(" + index + ")").children("td:eq(2)").html());
                newInvoiceItemServObj.total = parseInt($("#tblViewInvoiceItemServ").children("tbody").children("tr:eq(" + index + ")").children("td:eq(3)").html().replace("₱", ""));
                newInvoiceItemServObj.invoice_number = $(".generated-invoice-number").html();
                newInvoiceItemServObj.status = "Active";
                newInvoiceItemServObj.created_at = result;
                newInvoiceItemServObj.updated_at = result;
                grandTotal += parseInt($("#tblViewInvoiceItemServ").children("tbody").children("tr:eq(" + index + ")").children("td:eq(3)").html().replace("₱", ""));
                newInvoiceItemServObj.grand_total = grandTotal;
                newInvoiceItemServObj.personnel_id = $("#txtCurrLoggedInId").val();
                if($("#txtInvoiceToName").val() == "") {
                    alert("Name of the invoice receiver is required");
                }else {
                    newInvoiceItemServObj.inv_to_name = $("#txtInvoiceToName").val();
                }
                if($("#txtInvoiceToAddress").val() == "") {
                    alert("Address of the invoice receiver is required");
                }else {
                    newInvoiceItemServObj.inv_to_address = $("#txtInvoiceToAddress").val();
                }
                if($("#txtInvoiceToPhoNum").val() == "") {
                    alert("Phone number of the invoice receiver is required");
                }else {
                    newInvoiceItemServObj.inv_to_phone_number = $("#txtInvoiceToPhoNum").val();
                }
                if($("#txtInvoiceToEmail").val() == "") {
                    alert("Email of the invoice receiver is required");
                }else {
                    newInvoiceItemServObj.inv_to_email = $("#txtInvoiceToEmail").val();
                }
                if($("#txtInvoiceToName").val() == "" || $("#txtInvoiceToAddress").val() == "" || $("#txtInvoiceToPhoNum").val() == "" || $("#txtInvoiceToEmail").val() == "") {
                    newInvoiceItemServArr.push(nullObject);
                    alert("All invoice receiver fields are required");
                }else {
                    alert("Success");
                    newInvoiceItemServArr.push(newInvoiceItemServObj);
                    $(".invoice-grand-total").html("₱" + grandTotal);
                    console.log(newInvoiceItemServArr);
                    $.ajaxSetup({
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                        }
                    });
                    $.ajax({
                        url: "{{ url('/invoice/add_invoice_item_serv') }}",
                        method: 'post',
                        data: { },
                        dataType: "json",
                        beforeSend:function(result){

                        },
                        success: function(result){
                            if(result["result"] == "Success"){
                                sweetAlert('Good job!', 'Item/Service information was successfully added.', 'success');
                            }
                        },
                        error: function(xhr, result, error){
                            sweetAlert('Error!', 'Item/Service information was not added. Check each fields for error or fill all the invoice to fields.', 'error');
                        }
                    });
                }
            }
        }
    }

This is the route:

Route::post('/invoice/add_invoice_item_serv', 'InvoiceItemServController@add_invoice_item_serv');

And this is the Controller:

public function add_invoice_item_serv(Request $request){
    $invoice = DB::table('invoices')
                ->where('invoice_number', '')
                ->count();

    if($invoice <= 0) {
        DB::table('invoices')->insert(
            [
                'invoice_number' => '',
                'grand_total' => '',
                'personnel_id' => '',
                'inv_to_name' => '',
                'inv_to_address' => '',
                'inv_to_phone_number' => '',
                'inv_to_email' => '',
                'invoice_status' => 'Active',
                'invoice_date' => date('Y-m-d'),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]
        );
    }else {
        DB::table('invoices')
        ->where('personnel_id', '')
        ->update([
            'grand_total' => '';
    }

    DB::table('invoice_item_servs')->insert(
        [
            'description' => '',
            'unit_price' => '',
            'quantity' => '',
            'total' => '',
            'invoice_number' => '',
            'invoice_item_serv_status' => 'Active',
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ]
    );

    return response()->json(['result'=>"Success"]);
}

You can convert it to JSON and send it

$(".invoice-grand-total").html("₱" + grandTotal);
console.log(newInvoiceItemServArr);
var requestData = JSON.stringify(newInvoiceItemServArr);

.................

$.ajax({
    url: "{{ url('/invoice/add_invoice_item_serv') }}",
    method: 'post',
    data: requestData,
    dataType: "json",

This should work.

In the controller you can access the request by $request->all()

and a foreach to iterate the array

and you can access the object and get the value by

$products = $request->all();
foreach($products as $product){
   $product->quantity;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM