Backend Development Laravel Subjective
Sep 30, 2025

Explain Database indexing strategies in Laravel with code examples.

Detailed Explanation
Database indexing improves query performance: **Creating Indexes in Migrations:**
Schema::table("users", function (Blueprint $table) {
    // Single column index
    $table->index("email");
    
    // Composite index
    $table->index(["status", "created_at"]);
    
    // Unique index
    $table->unique("username");
    
    // Full-text index
    $table->fullText(["title", "content"]);
});
**Index Types:**
// Primary key (automatic)
$table->id();

// Foreign key with index
$table->foreignId("user_id")->constrained();

// Custom index names
$table->index("email", "users_email_index");
**Query Optimization:**
// Use indexed columns in WHERE clauses
User::where("email", "john@example.com")->first();

// Composite index usage
User::where("status", "active")
    ->where("created_at", ">", now()->subDays(30))
    ->get();
**Dropping Indexes:**
$table->dropIndex("users_email_index");
$table->dropUnique("users_username_unique");
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback