php - Insert Multiple Records At Once With Laravel -
i inserting data rows 1 one, have heard somewhere requires time if there many data insert. ways of inserting them @ once?
public function add(request $request) { if ($request->ajax()) { $books = $request->books; foreach ($books $book) { if (!empty($book)) { $add = new book; $add->name = $book; $add->user_id = auth::user()->id; $add->save(); } } } }
insert multiple records using model
as others have pointed out, using query builder way insert multiple records @ time. fortunately laravel , eloquent orm coupled in many useful ways. coupling allows use model query builder instance set model.
// use auth; // use carbon; // use app\book; public function add(request $request) { if($request->ajax()) { // submitted books $books = $request->books; // book records saved $book_records = []; // add needed information book records foreach($books $book) { if(! empty($book)) { // current time $now = carbon::now(); // formulate record saved $book_records[] = [ 'name' => $book, 'user_id' => auth::user()->id, 'updated_at' => $now, // remove if not using timestamps 'created_at' => $now // remove if not using timestamps ]; } } // insert book records book::insert($book_records); } }
Comments
Post a Comment