Query optimization helps your app get data faster and use less computer power. It makes your website or app work smoothly.
Query optimization in Laravel
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Laravel
Model::where('column', 'value')->get(); // Use eager loading to avoid extra queries Model::with('relation')->get(); // Select only needed columns Model::select('column1', 'column2')->get();
Use where to filter data before fetching.
Eager loading with with() helps avoid many small queries.
Examples
Laravel
$users = User::where('active', 1)->get();
Laravel
$posts = Post::with('comments')->get();
Laravel
$products = Product::select('id', 'name', 'price')->get();
Sample Program
This example fetches only published posts with their authors. It loads author data with only id and name columns to save resources. It also selects only needed post columns.
Laravel
<?php use App\Models\Post; // Get posts with their author and only needed columns $posts = Post::with('author:id,name') ->select('id', 'title', 'author_id') ->where('published', 1) ->get(); foreach ($posts as $post) { echo "Title: {$post->title}, Author: {$post->author->name}\n"; }
Important Notes
Always test your queries with real data to see if optimization helps.
Use Laravel's debug tools like DB::listen() or packages like Laravel Debugbar to see queries.
Be careful not to over-optimize early; focus on queries that slow down your app the most.
Summary
Query optimization makes your app faster and lighter.
Use filtering, eager loading, and selecting only needed columns.
Check your queries with Laravel tools to find slow parts.
Practice
1. What is the main benefit of using eager loading in Laravel queries?
easy
Solution
Step 1: Understand eager loading purpose
Eager loading loads related data in one query instead of many separate queries.Step 2: Identify benefit in query optimization
By reducing the number of queries, it speeds up the app and lowers database load.Final Answer:
It reduces the number of database queries by loading related data upfront. -> Option AQuick Check:
Eager loading = fewer queries [OK]
Hint: Eager loading means load related data once, not many times [OK]
Common Mistakes:
- Confusing eager loading with caching
- Thinking it sorts or encrypts data
- Believing it loads data lazily
2. Which of the following is the correct way to select only the 'name' and 'email' columns from the users table in Laravel?
easy
Solution
Step 1: Recall Laravel query builder syntax
The method to specify columns is select(), and to get results is get().Step 2: Match correct syntax
$users = DB::table('users')->select('name', 'email')->get(); uses select('name', 'email')->get(), which is correct Laravel syntax.Final Answer:
$users = DB::table('users')->select('name', 'email')->get(); -> Option AQuick Check:
Select columns = select() + get() [OK]
Hint: Use select() to pick columns, then get() to fetch [OK]
Common Mistakes:
- Using non-existent methods like columns() or only()
- Confusing fetch() with get()
- Trying to fetch all columns without select()
3. Given the code below, what will be the number of queries executed?
Post::with('comments')->where('status', 'published')->get();medium
Solution
Step 1: Understand eager loading with 'with'
The with('comments') loads related comments in a separate query.Step 2: Count queries executed
One query fetches posts with status 'published', second query fetches all related comments.Final Answer:
2 queries -> Option DQuick Check:
with() = 2 queries [OK]
Hint: with() runs 2 queries: main + related data [OK]
Common Mistakes:
- Thinking with() runs only 1 query
- Assuming one query per post for comments
- Confusing with() with lazy loading
4. Identify the problem in this Laravel query that causes slow performance:
$users = User::all();
foreach ($users as $user) {
echo $user->profile->bio;
}
medium
Solution
Step 1: Analyze query and loop
User::all() loads all users but does not load related profiles eagerly.Step 2: Identify N+1 query problem
Accessing $user->profile inside loop triggers one query per user, causing many queries.Final Answer:
Using all() loads all users without eager loading profiles, causing N+1 queries. -> Option CQuick Check:
all() without eager loading = N+1 queries [OK]
Hint: Use with('profile') to avoid N+1 queries [OK]
Common Mistakes:
- Blaming loop syntax instead of query
- Assuming profile relation missing without checking
- Thinking echo slows query performance
5. You want to optimize a query that fetches posts with their authors and comments, but only need the post title, author name, and comment content. Which approach is best?
hard
Solution
Step 1: Understand data needed
Only post title, author name, and comment content are required, so select only these columns.Step 2: Apply eager loading with column selection
Use with() to eager load authors and comments, and select() to limit columns for optimization.Final Answer:
Use eager loading with select() on posts, authors, and comments to fetch only needed columns. -> Option BQuick Check:
Eager load + select columns = best optimization [OK]
Hint: Combine eager loading and select() to fetch only needed data [OK]
Common Mistakes:
- Fetching all columns wastes resources
- Using lazy loading causes many queries
- Merging in PHP is slower than optimized queries
