Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mesqueeb's avatar

How can I send an array through Ajax and do a bulk "insert" into the DB?

I have a task list app with Vuejs + Laravel. I want to be able to do an ajax post request to store multiple tasks at once.

My code for posting 1 task works like below, but when making an array of it and doing an "insert" instead of "create" on the DB it crashes.

Workflow for 1 task:

##Ajax request:

this.$http.post('/api/items',newItem) // newItem is an object

##Ajax Controller:

public function store(Request $request)
{
    return Item::create($request->all());
}

Now I tried with an array of newItems instead:

newItemArray = [newItemA, newItemB];
this.$http.post('/api/items',newItemArray) // send array

public function store(Request $request)
{
    if (is_array ($request->all())){
        return Item::insert($request->all());
    }
    return Item::create($request->all());
}

But I get the following bug:

UnexpectedValueException in Response.php line 399: The Response content must be a string or object implementing __toString(), "boolean" given.

Obviously I cannot send an array it seems.

How can I send an array through Ajax and do a big "insert" into the DB?

0 likes
6 replies
Snapey's avatar

you can't do that with a request object. it contains far more than just your data.

extract the data from the request, then check if its an array.

Sanni's avatar

this.$http.post('/api/items',JSON.stringify(newItemArray)) // send array

mesqueeb's avatar

@Snapey How do I extract the data from the request?

@Sanni that didn't work! I get the following error now:

preg_replace(): Parameter mismatch, pattern is a string while replacement is an array

elbgoods's avatar

Javascript (ECMA2015):

data = {
newItemArray: [newItemA, newItemB]
}

this.$http.post('/api/items',JSON.stringify(data)) // send array

Laravel:

public function store(Request $request)
{
    if (is_array ($request->input('newItemArray'))) {
        .....
    }

    .....
}
1 like
jekinney's avatar

Sending an array, unless you always send an array is very inconsistent. Also a higher payload then an json object. This is what json was created for a standard of sending data. Otherwise xml and soap would still be huge, though that still isn't an array.

Laravel sets json to an php object by default with Request. So I suggest using json to send your data, access the data via the request object. By default with eloquent you have to loop over your request (if many json objects) and create in your loop.

foreach($request->all() as $data) { Item::create($data); }

I've had an issue a long time ago where I ended up doing:

$item = new Item(); $item->create($data);

Don't forget dd() your request and network tab in dev tools or postman to ensure what and what format data is being sent and received.

Please or to participate in this conversation.