Home > front end >  How to post lots of data to laravel database
How to post lots of data to laravel database

Time:09-18

I am trying to submit this data to a database in Laravel. My intention is to submit all at the same time, this is just two rows but I would like to send them together even if it gets to 10 rows I can submit.

0: {item: "Electronics", subitem: "Laptop", subitem2: "Hard D", unit: "Length - meter (m)"}
1: {item: "Electronics", subitem: "Laptop", subitem2: "Hard D", unit: "Length - meter (m)"}

What I have tried

  for ($i = 1; $i < count($request->all()); $i  ) {

    $answers[] = [
        'item' => $request->item[$i],
        'subitem' => $request->subitem[$i],
        'subitem2' => $request->subitem2[$i]
    ];

I tried to do a for loop using the above code but its not working..got the below error

count(): Parameter must be an array or an object that implements Countable

CodePudding user response:

So after discussion in comments the solution for what you are trying to achieve can be:

foreach ($request->all() as $data){
  Items::insert([
       'item' => $data['item'],
       'subitem' => $data['subitem'],
       'subitem2' => $data['subitem2'],
       'unit' => $data['unit']
  ]);
}

If you don't have a model and you literally insert using DB facade then you can do:

  DB::table('items')->insert([
       'item' => $data['item'],
       'subitem' => $data['subitem'],
       'subitem2' => $data['subitem2'],
       'unit' => $data['unit']
  ]);

But you must build dedicated models.

Also you need to validate your input, $request->all() is way too general but this is a suggestion for future improvements and something to keep in mind.

Don't trust the data that the users are sending from the front-end. Back-end should always validate.

CodePudding user response:

Take a look at the laravel documentation here: https://laravel.com/docs/8.x/queries#insert-statements

Here is an example of they use for inserting multiple records

DB::table('users')->insert([
    ['email' => '[email protected]', 'votes' => 0],
    ['email' => '[email protected]', 'votes' => 0],
]);
  • Related