Laravel interview question · Most asked

Eloquent or the query builder: when do you use which?

Summary

Eloquent is the ActiveRecord ORM: models, relationships, events, casts and accessors. The query builder builds SQL fluently and returns plain objects. Both use PDO with bound parameters.

Longer Answer

Eloquent is the default for domain data: relationships, mass-assignment protection, casts, model events, scopes and API resources all build on it. It costs memory and CPU per row because every row becomes a full model object.

The query builder (DB::table('orders')) is lighter and better for reporting queries, bulk updates and inserts, large exports, and complex SQL (aggregates, window functions, CTEs through DB::raw or selectRaw). Bulk operations through either the builder or Model::query()->update() skip model events, which is often what you want for performance but surprising if observers do important work.

Raw SQL is fine when needed; always pass values as bindings (DB::select('... where id = ?', [$id])).

Key Points

  • Eloquent: models, relationships, events; heavier per row.
  • Query builder: lighter; reports, bulk work, complex SQL.
  • Bulk updates skip model events.
  • Always bind values in raw SQL.

More most-asked Laravel questions

← All Laravel questions