I need to store exactly three pages at once via form. I would like save in similar manner as model save() method, because this will automatically update record timestamps.
How to do this for multiple records at once?
My page Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Page extends Model{
protected $table = 'simple_pages';
}
My code:
public function createPages(Request $request){ // I use Page at the top
$data = [
[
'title'=> $request->first,
'content'=> $request->firstCont
],[
'title'=> $request->second,
'content'=> $request->secondCont
][
'title'=> $request->third,
'content'=> $request->thirdCont
]
];
Page::unguard();
$pages = new Page($data);
$pages->save(); // Something like this would be amazing
Page::reguard();
}
Note: I am strongly against creating multiple instances of Page model, and then Loop them to save them each individualy. Also, I dont want to use DB insert, because it will not update record timestamps automaticaly.
After long long search looks like I found this:
$eloquentCollection->each(function ($item, $key) {
$item->save();
});
Yes, it is Iteration, but looks like there are no other methods how to save multiple models. The only alternative is to use DB::insert()
, but be aware of not having automaticaly updated timestamps.
Also, if you are willing to have too much eloquent models to save, save them by chunks because of possible memory issues (or push them into Queue
).