How to Insert Multiple Rows from a Single Query Using Eloquent/Fluent

How to insert multiple rows from a single query using eloquent/fluent

It is really easy to do a bulk insert in Laravel using Eloquent or the query builder.

You can use the following approach.

$data = [
['user_id'=>'Coder 1', 'subject_id'=> 4096],
['user_id'=>'Coder 2', 'subject_id'=> 2048],
//...
];

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

In your case you already have the data within the $query variable.

How to insert multiple rows in laravel, need explanation

Please refer How to insert multiple rows from a single query using eloquent/fluent there is a solution for both eloquent and querybuilder

      $data = [
['user_id'=>'Coder 1', 'subject_id'=> 4096],
['user_id'=>'Coder 2', 'subject_id'=> 2048],
];
Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach

insert multiple records at once in laravel eloquent

You can do this with model:

Model::insert([ 
['name' => 'foo'],
['name' => 'bar'],
['name' => 'baz']
]);

But here insert is the same QB method.

How to insert multiple rows in pivot table using Eloquent?

$user->machine()->attach($user->id, ['machine_id' => $machines]);

That ain't right. You already have $user, and you want to attach a specific machine, so you need to pass that id to machines()->attach():

$user = User::create($validatedUserData);
$machine = ...;
// Not sure how you're getting `$machines`, and it should be singular `$machine`

$user->machines()->attach($machine->id, [...]);
// Replace `[...]` with any additional columns.

Note, if you want to attach multiple, you use attach() or sync():

$user->machines()->attach($machines);
$user->machines()->sync($machines);

attach() is best used if you have existing records attached, as sync() will detach() then attach() the ids you're passing. Also, if you need additional columns, adjust your $machines to be an associative array:

$machines = [
1,
2 => ["additional" => "column"],
3
]; // Etc. etc.

How to insert multiple records to database using Laravel Eloquent

You're getting that error because you have no id form field. Try this:

public function store(Request $request)
{
$input = Input::all();
$condition = $input['name'];
foreach ($condition as $key => $condition) {
$student = new Student;
$student->name = $input['name'][$key];
$student->fname = $input['fname'][$key];
$student->rollno = $input['rollno'][$key];
$student->obtainedmarks = $input['obtainedmarks'][$key];
$student->totalmarks = $input['totalmarks'][$key];
$student->percentage = $input['percentage'][$key];
$student->save();
}
return view('students.index');
}


Related Topics



Leave a reply



Submit