-2

I have an array in the post request as an example below:

$data = array(
    array('title'=>'1st title', 'desc'=>'desc'),
    array('title'=>'2nd title', 'desc'=>'desc'),
    array('title'=>'3rd title', 'desc'=>'desc'),
)

Is there a way in Laravel using Eloquent I can save above data without using foreach? Note that the array keys which I am getting in the request is not same as column names of the table.

  • 2
    Possible duplicate of [How to insert multiple rows from a single query using eloquent/fluent](https://stackoverflow.com/questions/29723865/how-to-insert-multiple-rows-from-a-single-query-using-eloquent-fluent) – Rahul Apr 11 '19 at 11:05
  • Its not, it is a little different, please check description again. – Danish Hakim Khan Apr 11 '19 at 11:14
  • So can you tell us what are column names which are relevant to request keys so that we can map it to? – Rahul Apr 11 '19 at 11:16
  • request array has 'title' key and db column is article_title. Same goes for other four columns, I think I still have to run a foreach to make the mapping data as per table schema. – Danish Hakim Khan Apr 11 '19 at 11:19

3 Answers3

2

I hope this would help you

$data = [
    ['title' => '1st title', 'desc' => 'desc'],
    ['title' => '2nd title', 'desc' => 'desc']
    .....
];

DB::table('users')->insert($data);

Put all the values you want to insert in to an array and then pass it to the insert function.

Source: https://laravel.com/docs/5.1/queries#inserts

Sethu
  • 1,299
  • 10
  • 13
  • i believe the array keys has to be the table column names which is not in my case, column names are different then the array keys and to make above array, I think I still have to run a foreach. – Danish Hakim Khan Apr 11 '19 at 11:12
  • 1
    if the keys are different yes, you need to use foreach – Sethu Apr 11 '19 at 11:13
0

try this:

DB::table('table_name')->insert($data);
PHP Geek
  • 3,949
  • 1
  • 16
  • 32
0

Using eloquent: just as mentioned by Sethu, but a few lines will be:

Model::insert($data); // eg: Posts::insert($your_request_array);

Just pass in the array directly here: above will return true on success.

Johhn
  • 979
  • 17
  • 24