Query Builder vs. Eloquent Model in Laravel Query optimization code example from several project
1. Query Builder
Query Builder provides a direct way to interact with the database using SQL-like queries. It does not require defining models and relationships.
When to Use Query Builder?
✅ When performance is critical (especially for large datasets).
✅ When executing complex queries (e.g., JOIN, GROUP BY, HAVING).
✅ When fetching raw data without needing relationships or models.
✅ When dealing with reports, analytics, or bulk operations.
Example of Query Builder:
✅ Query Builder is faster than Eloquent because it does not load extra objects, relationships, or unnecessary data.
2. Eloquent ORM
Eloquent is Laravel’s Object-Relational Mapping (ORM) that allows you to work with database tables as if they were PHP objects.
When to Use Eloquent?
✅ When working with models and relationships (like hasOne, belongsTo).
✅ When you need an expressive and readable syntax for database operations.
✅ When you want to leverage Laravel’s built-in features like accessors, mutators, scopes, and event handling.
✅ When developing standard CRUD applications.
Example of Eloquent:
✅ Eloquent makes the code more readable and maintainable.
❌ But Eloquent can be slower than Query Builder because it loads additional model data.
Performance Comparison
| Feature | Query Builder | Eloquent Model |
|---|---|---|
| Performance | ✅ Faster (No overhead) | ❌ Slower (Loads models & relationships) |
| Readability | ❌ Complex Queries | ✅ More readable & expressive |
| Relationships | ❌ Manual Joins Required | ✅ Built-in relationship methods |
| Use Case | Complex queries, Reports | Standard CRUD, Object-Oriented Approach |
Which One Should You Use?
-
For standard CRUD operations: 🏆 Use Eloquent Model (more readable, easy to maintain).
-
For complex queries, bulk updates, or reports: 🏆 Use Query Builder (better performance).
-
For raw SQL or stored procedures: 🏆 Use DB::select() for direct queries.
Hybrid Approach (Using Both)
You can combine Eloquent with Query Builder for efficiency. Example:
This optimizes performance while still using Eloquent.
Final Verdict:
✔ If you prioritize speed, use Query Builder.
✔ If you prioritize readability & maintainability, use Eloquent.
✔ For best results, mix both based on the situation.
👉 Pro Tip: If your application is getting slow, optimize Eloquent queries using select(), chunk(), cache(), or even raw queries when necessary.
==========================================================
Here are advanced query optimization techniques in Laravel with both Query Builder and Eloquent Model approaches. These techniques will help you handle complex queries efficiently.
Scenario:
Imagine you have an e-commerce system where you need to:
-
Fetch products with their category, total sales count, and average rating.
-
Only fetch active products that have at least 5 sales.
-
Sort products by highest rating first, then by most sales.
-
Implement pagination for better performance.
1️⃣ Query Builder Approach (Optimized for Speed)
✅ Optimizations Used:
✔ JOIN instead of multiple queries for efficient data retrieval.
✔ COUNT(sales.id) for total sales instead of looping in PHP.
✔ AVG(reviews.rating) for product rating using DB::raw().
✔ HAVING COUNT(sales.id) >= 5 to filter high-selling products.
✔ ORDER BY optimized to sort by rating first, then sales.
✔ paginate(10) to limit records per page, reducing load.
2️⃣ Eloquent Model Approach (Readable & Maintainable)
✅ Optimizations Used in Eloquent:
✔ with(['category', 'sales', 'reviews']) for eager loading (prevents N+1 query issue).
✔ withCount('sales as total_sales') instead of running multiple queries for sales count.
✔ withAvg('reviews as average_rating', 'rating') for efficient rating calculation.
✔ having('total_sales', '>=', 5) to filter high-selling products.
✔ orderByDesc('average_rating') & orderByDesc('total_sales') for sorting.
✔ paginate(10) for performance-friendly pagination.
🔍 Performance Comparison
| Feature | Query Builder ✅ (Fast) | Eloquent ❌ (Slower) |
|---|---|---|
| Performance | Faster (raw SQL) | Slower (loads models) |
| Readability | Harder to read | Easier to maintain |
| Eager Loading | Manual joins required | with() handles N+1 issue |
| Aggregations | DB::raw() needed | withCount() & withAvg() |
| Pagination | Efficient | Slightly heavier |
🚀 When to Use Which?
-
Query Builder: ✅ Best for complex reports, huge datasets, and high-performance queries.
-
Eloquent: ✅ Best for CRUD operations, small-to-medium datasets, and developer-friendly code.
-
Hybrid Approach: Use Query Builder for heavy queries & Eloquent for normal operations.
🔥 Extra Optimization Tips
-
Use Indexing in Database: Index frequently queried columns like
status,category_id. -
Use Caching: Store frequently accessed queries in Redis or Laravel Cache.
-
Chunk Large Queries: Use
chunk()for bulk data processing. -
Avoid Loading Unnecessary Columns: Use
select()to fetch only required fields. -
Lazy vs. Eager Loading: Use
with()to avoid N+1 queries.
Final Thoughts
✔ Use Query Builder for high-performance queries, reports, and analytics.
✔ Use Eloquent for regular CRUD operations with relationships.
✔ Optimize both using eager loading, pagination, and caching.
Here are more complex query optimization examples using Query Builder and Eloquent in Laravel, covering different real-world scenarios.
1️⃣ E-Commerce System: Fetch Products with Inventory & Discounted Price
Goal:
-
Fetch products with category, inventory stock, discount price, and total sales.
-
Show only in-stock products and apply a discount when available.
-
Sort by highest discount percentage.
✅ Query Builder Approach (Faster & Optimized)
✅ Eloquent Approach (Readable & Maintainable)
2️⃣ Social Media Platform: Fetch Posts with Comments & Likes Count
Goal:
-
Get posts with user details, comment count, and like count.
-
Fetch only public posts created within the last 30 days.
-
Sort by most liked posts first.
✅ Query Builder Approach
✅ Eloquent Approach
3️⃣ Banking System: Fetch Users with Their Total Transactions & Balance
Goal:
-
Fetch users with their total deposits, withdrawals, and balance.
-
Exclude users with zero transactions.
-
Sort by highest balance first.
✅ Query Builder Approach
✅ Eloquent Approach
4️⃣ HR System: Fetch Employees with Attendance & Leave Count
Goal:
-
Get employees with attendance count and leave count.
-
Show only employees who have worked for at least 20 days in the month.
-
Sort by highest attendance first.
✅ Query Builder Approach
✅ Eloquent Approach
🚀 Advanced Optimization Techniques
-
Use Indexing in Database:
-
Use Caching (Redis, Laravel Cache):
-
Chunk Large Queries:
-
Use
select()to Avoid Loading Unnecessary Columns:
📌 Final Verdict
-
Use Query Builder ✅ when working with large datasets and need maximum speed.
-
Use Eloquent ✅ when working with CRUD operations and need developer-friendly syntax.
-
Use a hybrid approach 🏆 to combine performance & maintainability.
Here are more complex query optimization examples from large-scale projects like E-commerce, Banking, Social Media, and Enterprise Resource Planning (ERP) Systems using Query Builder and Eloquent.
1️⃣ E-Commerce System: Fetch Orders with Customer, Payment & Shipping Details
Goal:
-
Fetch orders with customer details, total items, total amount, payment status, and shipping details.
-
Show only completed orders from the last 3 months.
-
Sort by highest total amount.
✅ Query Builder Approach (Faster & Optimized)
✅ Eloquent Approach (Readable & Maintainable)
2️⃣ Banking System: Fetch Customers with Their Total Transactions & Loan Balances
Goal:
-
Fetch customers with their total deposits, total withdrawals, total loans, and remaining balance.
-
Exclude customers with zero transactions.
-
Sort by highest balance first.
✅ Query Builder Approach
✅ Eloquent Approach
3️⃣ Social Media System: Fetch Most Popular Posts with Engagements
Goal:
-
Fetch posts with user details, total comments, total likes, and total shares.
-
Only fetch public posts from the last 7 days.
-
Sort by total engagement score (likes + comments + shares).
✅ Query Builder Approach
✅ Eloquent Approach
🚀 Large Project Optimization Techniques
✅ 1. Use Indexing in Database
✅ 2. Use Caching (Redis, Laravel Cache)
✅ 3. Use Chunking for Large Queries
✅ 4. Use select() to Avoid Unnecessary Data Load
📌 Final Verdict
-
Use Query Builder ✅ when working with large datasets that require maximum speed.
-
Use Eloquent ✅ for CRUD operations and developer-friendly syntax.
-
Use Hybrid Approach 🏆 by combining both for better performance & maintainability.
No comments