Laravel - Relationships - One To Many

A one-to-many relationship is used to define relationships where a single model is the parent to one or more child models. For example, a blog post may have an infinite number of comments. Like all other Eloquent relationships, one-to-many relationships are defined by defining a method on your Eloquent model:


Remember, Eloquent will automatically determine the proper foreign key column for the Comment model. By convention, Eloquent will take the "snake case" name of the parent model and suffix it with _id. So, in this example, Eloquent will assume the foreign key column on the Comment model is post_id.

Once the relationship method has been defined, we can access the collection of related comments by accessing the comments property. Remember, since Eloquent provides "dynamic relationship properties", we can access relationship methods as if they were defined as properties on the model:

    use App\Models\Post;
    $comments = Post::find(1)->comments;
    foreach ($comments as $comment) {

Since all relationships also serve as query builders, you may add further constraints to the relationship query by calling the comments method and continuing to chain conditions onto the query:

    $comment = Post::find(1)->comments()
                        ->where('title', 'foo')

Like the hasOne method, you may also override the foreign and local keys by passing additional arguments to the hasMany method:

    return $this->hasMany(Comment::class, 'foreign_key');
    return $this->hasMany(Comment::class, 'foreign_key', 'local_key');