BelongsTo
BelongsTo is a relationship type used in Laravel's Eloquent ORM to define the inverse of a one-to-many or one-to-one association. It indicates that the current model belongs to another model, which holds the foreign key. In database terms, the child table contains a foreign key referencing the parent table (for example, a comments table with post_id referencing posts.id).
In Eloquent, you declare it in the child model with a method named after the relationship, returning
return $this->belongsTo(Post::class);
}
}
Usage typically involves accessing the related model via the relation property, such as $comment->post, which returns
The foreign key and the related key can be overridden. For example:
return $this->belongsTo(Post::class, 'custom_post_id', 'custom_id');
By default, the foreign key is the snake_case name of the relationship method with _id appended (e.g.,
Relation direction and alternatives:
BelongsTo is defined on the child side of the relationship. The opposite side is usually defined with