One-to-Many Relationships in Laravel Eloquent
This article explains how to define and use one-to-many and inverse (belongsTo) relationships in Laravel's Eloquent ORM, including default foreign key conventions, accessing related records, applying query constraints, and customizing foreign and local keys with code examples.
One-to-many relationships allow a single model to own an unlimited number of related models, such as a blog post that can have many comments.
In an Eloquent model you define a method that returns $this->hasMany('App\Comment') . Laravel automatically determines the foreign key post_id by using the snake‑case form of the parent model name with an _id suffix.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
}
?>After defining the relationship you can retrieve the comment collection via the dynamic comments property, e.g.:
$comments = App\Post::find(1)->comments;
foreach ($comments as $comment) {
// process each comment
}Because relationships are also query builders, you can chain additional constraints on the comments method:
$comment = App\Post::find(1)->comments()
->where('title', 'foo')
->first();If you need to customize the foreign key or local key, you can pass them as extra arguments to hasMany :
return $this->hasMany('App\Comment', 'foreign_key');
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');Inverse One-to-Many (belongsTo)
To retrieve the parent model from a child, define a belongsTo method in the child model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post');
}
}
?>Now you can access the related post via the dynamic post property:
$comment = App\Comment::find(1);
echo $comment->post->title;If the foreign key on the child model is not the default post_id , pass the custom key as the second argument to belongsTo . To use a different local key on the parent model, provide a third argument:
return $this->belongsTo('App\Post', 'foreign_key', 'other_key');These conventions and customizations give you full control over how Laravel maps one-to-many relationships between tables.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.