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.