boby
3 weeks ago
193
11
Laravel

Ajax array of objects to DB

Posted 3 weeks ago by boby

Hi, I am little stuck :)

I am sending this from my view to my controller via ajax:

{
	"number": "0001/2020",
	"title": "Test invoice 1",
	"customer_id": "1",
	"invoice_date": "2020-03-13",
	"articles": [
		{
			"name": "article1",
			"price": "55.99",
			"quantity": "1",
			"total": "55.99"
		},
		{
			"name": "article2",
			"price": "44.99",
			"quantity": "2",
			"total": "89.98"
		}
	]
}

in my controller I save invoice like this:

        $attributes = $this->validateInvoice();
        $attributes['user_id'] = Auth::user()->id;
        $articles = $attributes['articles'];

        foreach ($articles as $article) {
             $attributes['total'] += (float)($article['total']);
        }        
        $invoice = Invoice::create($attributes);

and this is saved ok in DB.

now I want to save articles in other table:

        $articles = $articles->toArray();
        $articles['invoice_id'] = $invoice->id;
        InvoiceArticle::insert($articles);

but this throws:

Call to a member function toArray() on array

My $articles are array, but array of objects, not array of arrays.

Please sign in or create an account to participate in this conversation.