Introduction
Laravel’s Eloquent ORM is one of the most powerful and developer-friendly features in the entire framework. It transforms database interactions into clean, expressive, and readable PHP code. Instead of manually writing long SQL statements, Eloquent allows you to describe your queries using elegant, object-oriented syntax. This not only makes your code shorter but also easier to understand, maintain, and scale.
Fetching data is one of the core duties of any application, and Eloquent is built to make that effortless. Whether you’re retrieving all rows, filtering with conditions, eager loading relationships, paginating datasets, or performing advanced queries, Eloquent provides a smooth workflow. The simplest examples look like:
Product::all();
Product::find(1);
Product::where(‘price’, ‘>’, 50)->get();
These straightforward lines replace complex SQL with intuitive PHP commands. This long, detailed post explores Eloquent deeply, focusing especially on how to fetch data efficiently and cleanly.
What Is Eloquent?
Eloquent is Laravel’s built-in ORM (Object Relational Mapper). It turns your database tables into models—PHP classes that represent rows and relationships. Instead of manually writing SQL queries, you interact with your data through expressive methods.
Each model corresponds to a table. For example:
- Product model → products table
- User model → users table
- Order model → orders table
Eloquent automatically handles table naming, timestamps, primary keys, and relationships using conventions.
This convention-driven approach saves you time, reduces errors, and keeps your code extremely readable.
Why Eloquent Is Better Than Raw SQL
Readability
Instead of writing:
SELECT * FROM products WHERE price > 50;
You write:
Product::where(‘price’, ‘>’, 50)->get();
This is easier to read and understand, especially for developers who may not be SQL experts.
Maintainability
If your queries change, updating PHP code is easier than modifying raw SQL across your codebase.
Security
Eloquent automatically prevents SQL injection by binding parameters safely.
Integration
Eloquent works seamlessly with:
- Relationships
- Collections
- Blade templates
- Controllers
- Resources
- APIs
This makes it easier to build complete features quickly.
Testability
Eloquent queries can be mocked, making unit testing much more comfortable compared to raw SQL.
Basic Data Fetching Methods
Fetch All Records
To retrieve all rows from a table:
Product::all();
This returns a collection of Product objects. Every row becomes an object instance with attributes like name, price, category, and so on.
Find by Primary Key
To fetch a single record by ID:
Product::find(1);
If the record exists, you get a Product object. If not, null is returned.
findOrFail
If you want an exception when no record is found:
Product::findOrFail(1);
Laravel throws a 404 error automatically, which simplifies error handling in controllers.
First Record Matching Criteria
To fetch the first record that matches a condition:
Product::where(‘price’, ‘>’, 50)->first();
This returns one Product instance or null.
firstOrFail
Similar to findOrFail:
Product::where(‘price’, ‘>’, 50)->firstOrFail();
Using where() for Conditional Fetching
Basic Conditions
Where queries are extremely flexible:
Product::where(‘price’, ‘>’, 50)->get();
You can chain multiple conditions:
Product
::where(‘category’, ‘Electronics’)
->where(‘price’, ‘>’, 1000)
->get();
Using orWhere
To apply OR logic:
Product
::where(‘price’, ‘<‘, 50)
->orWhere(‘stock’, ‘<‘, 10)
->get();
Using whereIn
To match multiple values:
Product::whereIn(‘category_id’, [1, 3, 7])->get();
Using whereBetween
To filter price ranges:
Product::whereBetween(‘price’, [100, 500])->get();
Using whereNull and whereNotNull
To find rows with missing or present values:
Product::whereNull(‘description’)->get();
Product::whereNotNull(‘description’)->get();
Using whereDate
For date comparisons:
Order::whereDate(‘created_at’, ‘2024-11-01’)->get();
Eloquent makes even complex conditions easy to write.
Using Comparisons and Operators
Eloquent supports all major SQL operators:
- =
- !=
- <
- =
- <=
- like
- not like
Example:
Product::where(‘name’, ‘like’, ‘%phone%’)->get();
Fetching Specific Columns
Using select
To fetch only certain columns:
Product::select(‘name’, ‘price’)->get();
Add expression columns
You can even add computed values:
Product::select(‘name’, ‘price’, DB::raw(‘price * 0.9 as discounted_price’))->get();
This replaces complex SQL and keeps the code readable.
Ordering and Sorting Data
orderBy
To sort data:
Product::orderBy(‘price’, ‘asc’)->get();
orderByDesc
Descending order:
Product::orderByDesc(‘created_at’)->get();
multiple order rules
Product
::orderBy(‘category_id’)
->orderByDesc(‘price’)
->get();
Sorting becomes simple and structured.
Limiting and Skipping Records
limit
Product::limit(10)->get();
skip
Product::skip(5)->take(10)->get();
This is useful for custom pagination or when processing large datasets.
Fetching Single Column Values
pluck
pluck allows retrieving only a single column or key-value pairs:
Product::pluck(‘name’);
Key-value example:
Product::pluck(‘name’, ‘id’);
value
Fetch only one value:
Product::where(‘id’, 1)->value(‘price’);
This is efficient when you only need one number or string.
Using Aggregates
Eloquent supports common SQL aggregate functions:
count
Product::count();
sum
Product::sum(‘price’);
max and min
Product::max(‘price’);
Product::min(‘price’);
average
Product::avg(‘price’);
These make reporting and analytics simple.
Fetching Records with Relationships
Eloquent relationships are powerful. For example, if Product has many Reviews:
$product = Product::with(‘reviews’)->find(1);
To load multiple relationships:
Product::with([‘reviews’, ‘category’, ‘tags’])->get();
This avoids N+1 query problems and speeds up your applications.
Eager Loading vs Lazy Loading
Lazy Loading
If you load a product and then access its related reviews:
$product = Product::find(1);
$product->reviews;
This triggers multiple queries.
Eager Loading
Use with() to load everything in one query:
Product::with(‘reviews’)->find(1);
This improves performance dramatically.
Advanced Where Conditions
Nested where
Product::where(function($query) {
$query->where(‘price’, ‘>’, 100)
->where(‘stock’, ‘>’, 10);
})->get();
whereExists
Product::whereExists(function($query) {
$query->select(DB::raw(1))
->from(‘orders’)
->whereColumn(‘orders.product_id’, ‘products.id’);
})->get();
These advanced structures help build complex business logic with minimal SQL.
Pagination
Laravel offers built-in pagination that works with Eloquent.
paginate
Product::paginate(15);
simplePaginate
Product::simplePaginate(10);
cursorPaginate
Product::cursorPaginate(20);
Views automatically integrate with pagination UI links.
Chunking Large Data Sets
To process large datasets without memory overload:
Product::chunk(100, function($products) {
foreach ($products as $product) {
// process
}
});
This is crucial for background jobs or data exports.
Working with Collections
Eloquent returns results as Laravel collections. Collections have dozens of useful methods:
- filter
- map
- reduce
- groupBy
- sortBy
- each
- contains
Example:
$expensive = Product::all()->filter(function ($product) {
return $product->price > 500;
});
Collections give you immense power for post-query data processing.
Raw Expressions with Eloquent
Even though Eloquent aims to reduce SQL usage, you can still use raw expressions when needed:
Product::whereRaw(‘price > stock * 2’)->get();
Or:
Product::selectRaw(‘count(*) as total, category_id’)->groupBy(‘category_id’)->get();
Eloquent does not limit you—rather, it enhances your SQL workflow.
Caching Retrieved Data
To speed up performance, you can cache results:
Cache::remember(‘products_all’, 300, function () {
return Product::all();
});
Caching Eloquent responses significantly improves scalability.
Soft Deletes and Fetching
Models using SoftDeletes behave differently.
Soft deleted items are hidden by default:
Product::all();
Force include them:
Product::withTrashed()->get();
Fetch only deleted:
Product::onlyTrashed()->get();
Soft deletes preserve data while hiding it from normal queries.
Model Scopes
Scopes allow reusable query fragments.
Local scope
Define in model:
public function scopeExpensive($query)
{
return $query->where(‘price’, ‘>’, 1000);
}
Use it:
Product::expensive()->get();
Global scopes
Used for automatic filtering across all queries.
Performance Optimization Tips
Fetching data is easy, but doing it efficiently is crucial.
Use eager loading
Avoid lazy loading in loops.
Use select for large tables
Don’t fetch unnecessary columns.
Add indexes to frequently queried columns
Especially foreign keys or filters.
Cache heavy queries
Reduces database load.
Chunk for large processing
Prevents memory issues.
Best Practices When Fetching Data with Eloquent
Keep queries inside Models or Repositories
Avoid putting them in controllers.
Use scopes for common conditions
Keeps models clean.
Avoid deep nested queries
Refactor with relationships or scopes.
Use pagination for large result sets
Never load thousands of rows at once.
Use eager loading wisely
Only load relationships when needed.
Combining Fetching Techniques
Complex problems often require chaining multiple techniques together.
Example: Fetch products with high ratings, in stock, belonging to a specific category, sorted by popularity:
Product
::with([‘reviews’, ‘category’])
->where(‘stock’, ‘>’, 0)
->where(‘rating’, ‘>’, 4.5)
->where(‘category_id’, $categoryId)
->orderBy(‘sales’, ‘desc’)
->paginate(20);
Eloquent makes even advanced tasks look elegant.
Real-World Use Cases
Building Product Listings
Search, filter, paginate, sort—all easy with Eloquent.
Building Admin Panels
Dynamic tables, filters, and dashboards rely heavily on Eloquent queries.
API Endpoints
Eloquent integrates smoothly with JSON Resources.
Reporting and Analytics
Aggregates, grouping, and raw queries help generate dashboards.
Eloquent vs Query Builder vs Raw SQL
Laravel gives three ways to fetch data:
Eloquent
Simple, elegant, object-oriented.
Ideal for most use cases.
Query Builder
More control, faster in certain cases.
Useful when not needing models.
Raw SQL
Most flexible but least readable.
Use only for extremely complex operations.
Eloquent strikes the perfect balance between simplicity and power.
Leave a Reply