Database Indexing: Speed Up Queries the Right Way
Understand indexes, when to add them, and how to create indexes in Laravel migrations.
Olivia Bennett
October 11, 2025
3.6k85
Indexes make database lookups faster by allowing the database to find rows without scanning the entire table.
Indexes are helpful when you frequently filter or join by a column.
## Example: searching posts by user_id
If you often run:
- WHERE user_id = ?
Then indexing user_id improves performance.
## Add an index in a migration
```php
Schema::table('posts', function (Blueprint $table) {
$table->index('user_id');
});
```
## Composite index example
If you filter by both:
- user_id
- status
```php
$table->index(['user_id', 'status']);
```
## Graph: Full scan vs index
```mermaid
flowchart LR
A[Query WHERE user_id=5] --> B{Index exists?}
B -->|No| C[Scan all rows]
B -->|Yes| D[Jump to matching rows]
```
In the next tutorial, we will profile queries and catch slow endpoints.
#Laravel#Database#Performance#Advanced