0
0
Laravelframework~8 mins

Controller methods and actions in Laravel - Performance & Optimization

Choose your learning style9 modes available
Performance: Controller methods and actions
MEDIUM IMPACT
This affects server response time and how quickly the browser receives data to render the page.
Handling a web request with a controller method
Laravel
public function show($id) {
    $user = User::find($id);
    return view('user.profile', ['user' => $user]);
}
Queries only the needed user directly from the database, reducing processing time.
📈 Performance GainReduces server processing time by 90%, faster response delivery
Handling a web request with a controller method
Laravel
public function show($id) {
    $user = User::all()->where('id', $id)->first();
    return view('user.profile', ['user' => $user]);
}
Fetching all users and then filtering in memory is slow and uses more memory.
📉 Performance CostIncreases server CPU and memory usage, delays response by 100+ ms on large datasets
Performance Comparison
PatternServer ProcessingDatabase QueriesResponse TimeVerdict
Fetching all records then filteringHigh CPU and memoryInefficient, loads all dataSlow response[X] Bad
Direct query for needed recordLow CPU and memoryEfficient single queryFast response[OK] Good
Rendering Pipeline
Controller methods run on the server before the browser receives the HTML. Efficient methods speed up server response, allowing the browser to start rendering sooner.
Server Processing
Network Transfer
Browser Rendering
⚠️ BottleneckServer Processing
Core Web Vital Affected
LCP
This affects server response time and how quickly the browser receives data to render the page.
Optimization Tips
1Always query only the data you need in controller methods.
2Avoid loading large datasets before filtering in memory.
3Keep controller logic simple to reduce server processing time.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using direct database queries in controller methods?
AReduces server processing time by querying only needed data
BIncreases server memory usage
CMakes the browser render faster by skipping CSS
DImproves client-side JavaScript execution
DevTools: Network
How to check: Open DevTools, go to Network tab, reload the page, and check the time for the server response (usually the first request).
What to look for: Look for the 'Waiting (TTFB)' time; shorter times indicate faster server processing.