Database

Eloquent Relationships: Design & Mechanics

Senior Editor
Sep 27, 2026
9 min read

Explore hasMany, belongsTo, belongsToMany, and polymorphic relationships in Eloquent with proper foreign key indexing and cascading deletes.

The Power of Declarative Relationships

Eloquent allows you to define expressive object-relational mappings directly on models:

PHP
class Project extends Model
{
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function tasks(): HasMany
    {
        return $this->hasMany(Task::class);
    }
}

Foreign Key Indexes in Migrations

Defining an Eloquent relationship does not automatically index the foreign key in PostgreSQL! Always declare indexes in your schema migrations:

PHP
Schema::create('tasks', function (Blueprint $table) {
    $table->id();
    $table->foreignId('project_id')->constrained()->cascadeOnDelete();
    $table->string('title');
    $table->string('status')->default('todo')->index();
    $table->timestamps();
});

The cascadeOnDelete() constraint ensures referential integrity at the database layer.

Topics in this article

Related Knowledge Articles

Prevent partial data corruption during multi-table writes using DB::transaction() with automatic commit and rollback guarantees.
Understand how lazy loading triggers catastrophic N+1 database queries and how to prevent them using eager loading and Model::preventLazyLoading().
Learn how B-Tree, GIN, and partial indexes work in PostgreSQL to eliminate query bottlenecks and keep queries running under 5ms.