0
0
Laravelframework~10 mins

Query optimization in Laravel - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Query optimization
Write Eloquent Query
Laravel Builds SQL
Database Executes Query
Check Query Performance
Optimize Query
Repeat Until Efficient
This flow shows how Laravel builds and runs a database query, then checks and improves its performance step-by-step.
Execution Sample
Laravel
use App\Models\User;

$users = User::where('active', 1)
    ->orderBy('created_at', 'desc')
    ->limit(5)
    ->get();
This code fetches the 5 most recently created active users from the database.
Execution Table
StepActionLaravel Query Builder StateGenerated SQLDatabase ActionResult
1Start Eloquent QueryUser model, where active=1SELECT * FROM users WHERE active = 1Prepare queryNo data fetched yet
2Add orderByOrder by created_at DESCSELECT * FROM users WHERE active = 1 ORDER BY created_at DESCPrepare queryNo data fetched yet
3Add limitLimit 5 rowsSELECT * FROM users WHERE active = 1 ORDER BY created_at DESC LIMIT 5Prepare queryNo data fetched yet
4Execute get()Final query readySELECT * FROM users WHERE active = 1 ORDER BY created_at DESC LIMIT 5Run query5 user records returned
5Check performanceQuery runs in 120msN/AAnalyze query planIndex on active and created_at missing
6Optimize queryAdd index on active and created_atN/AAdd DB indexQuery runs faster
7Re-run optimized querySame querySELECT * FROM users WHERE active = 1 ORDER BY created_at DESC LIMIT 5Run query5 user records returned in 20ms
💡 Query optimized by adding index; execution time reduced from 120ms to 20ms
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 7
$usersnullnullnullnullCollection of 5 usersCollection of 5 users (faster)
Query SQLemptyWHERE active = 1ORDER BY created_at DESCLIMIT 5Final SQL queryFinal SQL query (same)
Execution TimeN/AN/AN/AN/A120ms20ms
Key Moments - 3 Insights
Why does adding an index speed up the query?
Adding an index helps the database find matching rows faster, as shown in step 6 and 7 where execution time drops from 120ms to 20ms.
Why is the query not executed until get() is called?
Laravel builds the query step-by-step but delays running it until get() is called, as seen in steps 1-3 where no data is fetched yet.
What does orderBy do in the query?
orderBy sorts the results by a column; here it sorts users by created_at descending, shown in step 2 updating the SQL.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the SQL query after step 3?
ASELECT * FROM users ORDER BY created_at DESC
BSELECT * FROM users WHERE active = 1 LIMIT 5
CSELECT * FROM users WHERE active = 1 ORDER BY created_at DESC LIMIT 5
DSELECT * FROM users
💡 Hint
Check the 'Generated SQL' column at step 3 in the execution table.
At which step does Laravel actually fetch data from the database?
AStep 2
BStep 4
CStep 6
DStep 1
💡 Hint
Look at the 'Database Action' and 'Result' columns to find when data is returned.
If we remove the limit(5), how would the execution table change?
AThe SQL query would not have LIMIT clause at step 3
BThe query would run faster
CThe query would not have WHERE clause
DThe query would order by ascending
💡 Hint
Compare the SQL query in step 3 with and without limit in the execution table.
Concept Snapshot
Laravel Query Optimization:
- Build queries step-by-step with Eloquent
- Query runs only when get() or similar is called
- Use orderBy, where, limit to control results
- Check query performance with DB tools
- Add indexes to speed up queries
- Repeat optimization until fast
Full Transcript
This visual trace shows how Laravel builds a database query using Eloquent. First, the query is constructed with conditions like where active=1, then ordered by creation date descending, and limited to 5 results. The SQL query is generated but not run until get() is called. The database executes the query and returns 5 user records. Performance is checked and found slow due to missing indexes. Adding an index on active and created_at columns speeds up the query significantly. The optimized query returns results much faster. Key points include that Laravel delays query execution until needed, indexes improve speed, and query parts like orderBy and limit shape the SQL. This step-by-step helps beginners see how query optimization works in Laravel.