简体   繁体   中英

Pass JSON data from AngularJS to Laravel Controller via POST

I am using AngularJS to POST data to a Laravel controller which then saves to a database.

I am running into a problem where the data I am passing from AngularJS to Laravel is not being parsed correctly.

This is the data I am passing through:

$scope.invoice_items = [
    {
        quantity: '1',
        price_per: '30',
        price_total: '30'
    },
    {
        quantity: '2',
        price_per: '5',
        price_total: '10'
    }
];

And this is my function:

$scope.createInvoice = function () {

    invoiceService.save($scope.invoice_items).success(function(somedata) {
        alert('successful!');
        console.log(somedata);
    }).error(function(data) {
        alert('not successful');
        console.log(data)
    });
};

And this is the service that sends the data:

save: function(invoiceData) {
        return $http({
            method: 'POST',
            url: 'http://localhost/blahblah',
            headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
            data: $.param(invoiceData)
        });
    }

And this is my Laravel controller:

public function store() {
    $input = request::all();

    return $input;
}

And finally, that $input only returns:

Object {undefined: ""}

So my question is. How do I pass in the data in my invoice_items into the laravel controller so it displays something like this:

invoice_items = [
    {
        quantity: '1',
        price_per: '30',
        price_total: '30'
    },
    {
        quantity: '2',
        price_per: '5',
        price_total: '10'
    }
];

Which then I can do a foreach in my Laravel controller to do whatever I want.

Ultimately I would like to do this in my laravel controller:

foreach(invoice_items as item) {
    echo item->quantity;
}

I hope that made sense. Anyone have an idea on how I can accomplish this?

Actually I figured it out!

The modification I made was in Angular Service:

data: invoiceService

That's without the $.param..

And in the Laravel controller all I did was:

return file_get_contents('php://input')

And that worked!

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