In the Laravel Eloquent documentation, there are methods, for example, Model::UpdateOrCreate() , but there are no examples of how to use these methods for multiple rows, in stackoverflow I found an example that suggests using a loop for multiple rows:

 foreach($users as $user){ User::create($user); } 

How appropriate is it to use a query query in a loop?

Could it be that Laravel uses asynchronous technologies, for example, queue or other features that allow to use such queries within a loop?

    1 answer 1

    On the githabab it was discussed: https://github.com/laravel/framework/issues/1295

    The following code creates as many queries as iterations.

     foreach ($users as $user) { User::create($user); } 

    This is what the author of Laravel wrote about it:

    It would be relatively easy to do this; however, events would not be fired. It is a timestamp insertion.

    Translation: it would be relatively easy to do; however, events will not run. This will only help insert the timestamp automatically.

    and this:

    Honestly just use the query builder for this. Will be much more efficient.

    Translation: Honestly, just use query builder for this. It will be much more efficient and make more sense.


    One of the users suggested the option below, but he also does not generate events:

     abstract class Model extends BaseModel { /** * @return string */ public static function table() { return with(new static)->table; } /** * Insert each item as a row. Does not generate events. * * @param array $items * * @return bool */ public static function insertAll(array $items) { $now = \Carbon\Carbon::now(); $items = collect($items)->map(function (array $data) use ($now) { return $this->timestamps ? array_merge([ 'created_at' => $now, 'updated_at' => $now, ], $data) : $data; })->all(); return \DB::table(static::table())->insert($items); } } 

    Example of use:

     Administrator::insertAll([ ['name' => 'Zane'], ['name' => 'Rob'], ]); 

    Source code