Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 multiple model save()

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.

like image 880
Fusion Avatar asked Apr 05 '16 19:04

Fusion


3 Answers

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).

like image 52
Fusion Avatar answered Nov 14 '22 20:11

Fusion


If you read the manual Mass Assignment.

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 = Page::create($data);
     Page::reguard();
}
like image 32
Ash Avatar answered Nov 14 '22 19:11

Ash


Here's the best solution I found to implement

User::create([array of multiple user detail arrays])

with avoid the need to executes as much queries as you have entries to add

Allow Eloquent to save multiple records at once

like image 3
Mahmoud Nassar Avatar answered Nov 14 '22 21:11

Mahmoud Nassar