Q1: How do you identify and fix N+1 query problems?
Identification: Use tools like Laravel Debugbar or Telescope to see the number of queries executed per request.
Fix: Use Eager Loading (with()) to load relationships in a single query.
// Bad (N+1)
$books = Book::all();
foreach ($books as $book) {
echo $book->author->name;
}
// Good (Eager Loading)
$books = Book::with('author')->get();
Q2: What are the different Cache drivers in Laravel?
Laravel supports multiple drivers via a unified API:
- file: Stores cached items in the filesystem (default).
- database: Stores items in a DB table.
- redis / memcached: In-memory stores. Best for high performance and distributed systems.
- array: Ephemeral cache for the current request (testing).
Q3: How does Route Caching and Config Caching improve performance?
Config Caching (php artisan config:cache): Combines all config files into a single file, reducing file I/O.
Route Caching (php artisan route:cache): Compiles all route registrations into a single method call, drastically speeding up route registration.
Note: These should only be used in production. Any changes to config/routes require clearing the cache.
Q4: How do you handle large datasets without running out of memory?
Chunking: The chunk() method retrieves a small subset of results at a time, processes them, and then fetches the next chunk.
User::chunk(100, function ($users) {
foreach ($users as $user) {
// Process user
}
});
Cursors: The cursor() method uses a generator to iterate through the database records one by one, keeping only one record in memory at a time. It is often more memory-efficient than chunking for simple iterations.
Q5: How can Queues improve application performance?
Offloading: Time-consuming tasks (sending emails, processing uploads, generating reports) should be offloaded to a background queue driver (Redis, SQS, Database) instead of running during the web request.
User Experience: This returns the response to the user immediately, making the application feel faster.
Dispatch After Response: For tasks that are quick but don't need to block the UI, you can use dispatchAfterResponse() to run the job after the HTTP response is sent to the browser (requires PHP-FPM).
Q6: What is Laravel Octane?
Overview: Octane supercharges Laravel's performance by serving the application using high-performance application servers like Swoole or RoadRunner.
Mechanism: Instead of booting the framework for every request (traditional PHP-FPM model), Octane boots the application once and keeps it in memory, handling requests across multiple workers. This can lead to significant speed improvements.
Considerations: You must be careful with memory leaks and state management (e.g., static variables persist between requests).
Q7: Why is Database Indexing critical for Laravel performance?
Problem: Eloquent makes it easy to write queries, but without indexes, the database must scan every row (Full Table Scan) to find results.
Solution: Always add indexes to columns used in WHERE, ORDER BY, and JOIN clauses via migrations.
Schema::table('users', function (Blueprint $table) {
$table->index('email'); // Single column index
$table->index(['first_name', 'last_name']); // Composite index
});
Q8: What is the N+1 problem and how do you solve it?
Problem: Executing one query to fetch a list of items, then executing an additional query for each item to fetch related data.
Solution: Use Eager Loading with the `with()` method.
// N+1 Problem
$posts = Post::all();
foreach ($posts as $post) {
echo $post->author->name; // Triggers a query for each post
}
// Solution
$posts = Post::with('author')->get(); // 2 queries total
Q9: Explain Database Indexing.
Concept: An index is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional writes and storage space.
Laravel: You can add indexes in migrations using `$table->index('column_name')`.
Best Practice: Index columns that are frequently used in `WHERE`, `ORDER BY`, and `JOIN` clauses.