Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in SQL by (20.3k points)

I have the following query:

  $query = UserSubject::where('user_id', Auth::id())->select('subject_id')->get();

and as expected I get the following result:

[{"user_id":8,"subject_id":9},{"user_id":8,"subject_id":2}]

Is there a way of copying the above result into another table so that my table looks like this?

ID|user_id|subject_id

1 |8      |9

2 |8      |2

The problem I have is that the $query can expect any number of rows and so I'm unsure how to iterate through an unknown number of rows.

1 Answer

+1 vote
by (40.7k points)

Try using the following code:

$data = array(

    array('user_id'=>'Coder 1', 'subject_id'=> 4096),

    array('user_id'=>'Coder 2', 'subject_id'=> 2048),

    //...

);

Model::insert($data); // Eloquent approach

DB::table('table')->insert($data); // Query Builder approach

But, your data is already within the $query variable.

Note: Bulk insert in Laravel using Eloquent or the query builder is easy to do.

Browse Categories

...