Home

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

class Comment extends Model {

public function post() {

return $this->belongsTo(Post::class);

}

}

Usage typically involves accessing the related model via the relation property, such as $comment->post, which returns

Customization and keys:

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

a
belongsTo
call.
Example:
the
associated
Post
model.
You
can
set
or
change
the
relation
with
$comment->post()->associate($post)
and
then
save
the
child
model.
Eager
loading
improves
performance
when
retrieving
multiple
children
with
their
parents
using
with('post').
post_id),
and
the
related
key
defaults
to
the
parent
model’s
primary
key,
typically
id.
hasMany
or
hasOne
on
the
parent
model.
Understanding
belongsTo
helps
structure
data
navigability
and
database
integrity
in
ORM-based
applications.