Home > OS >  Should I use Laravel Eloquent in this situation or Query Builder?
Should I use Laravel Eloquent in this situation or Query Builder?

Time:09-18

Should I use Query Builder for this in Laravel 9?

 DB::table('galleries')->insert(
 ['book_id' => $book->id, 'photo' => $name, 'cover' => 1],
 );

or Laravel Eloquent?

Gallery::create(
['book_id' => $book->id, 'photo' => $name, 'cover' => 1],
);

And what is the difference?

CodePudding user response:

They are both basically the same. The only difference comes when you want to insert a huge amount of data.

The performance of query builder is much faster than that of the eloquent ORM when handling VERY LARGE amounts of data.

CodePudding user response:

insert() Query builder method difference:
  1. 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.

  1. The second thing is, It is very fast and optimize in speed as compare to eloquent builder create() method.
  2. Third, It's not emits model events i.e. creating, created events etc.
  3. It's not returns created models in result.

create() eloquent method Difference:

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

  1. It emits model events i.e. creating, created events etc.

  2. It returns inserted model in result.

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

  • Related