insert() Query builder method difference:
- the difference is, Query Builder
insert()
runs mysql
raw insert query under the hood and As like mysql
raw query you can create multiple rows in single query.
DB::table('galleries')->insert(
['book_id' => $book->id, 'photo' => <photo A path>, 'cover' => 1],
['book_id' => $book->id, 'photo' => <photo B path>, 'cover' => 0],
);
The above query will insert two rows in single query.
- The second thing is, It is very fast and optimize in speed as compare to eloquent builder
create()
method.
- Third, It's not emits
model events
i.e. creating
, created
events etc.
- It's not returns created models in result.
create()
eloquent method Difference:
- It's insert only single row at a time. whenever you want insert multiple rows/models then you need to run
create()
method in foreach loop
or needs to use createMany()
method.
All of them works same like create()
. let suppose you want to insert 100 rows in database table then both will runs 100 insert
queries under the hood.
It emits model events i.e. creating
, created
events etc.
It returns inserted model in result.
It's slower than insert()
query builder method because it's handling a lot of computations, events pipelines during insertion.
Suggestion:
If you want to catch model event then must use eloquent()
. If you want query optimization, fast insertion and doesn't have any concern with model events
then user insert()
method.