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
- Gates or policies: how does authorization work in Laravel?
- What is the service container, and how does dependency injection work in Laravel?
- How do database transactions work in Laravel, and what pitfalls should you know?
- How do you validate requests in Laravel? Why use Form Requests?
- Which Artisan commands would you run when deploying Laravel to production, and why?
- What is the N+1 query problem in Eloquent and how do you prevent it?
- What is mass assignment, and how do $fillable and $guarded protect against it?
- How do queues work in Laravel?