0
0
Laravelframework~5 mins

One-to-many (hasMany) in Laravel

Choose your learning style9 modes available
Introduction

One-to-many relationships let you connect one item to many related items easily. It helps organize data that belongs together.

You have a blog post with many comments.
A user owns multiple orders in an online shop.
A category contains many products.
An author writes many books.
Syntax
Laravel
public function relatedItems()
{
    return $this->hasMany(RelatedItem::class);
}

This method goes inside the main model class.

Replace relatedItems and RelatedItem with your actual names.

Examples
This example shows a Post model with many Comment models.
Laravel
class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}
A User can have many Orders linked this way.
Laravel
class User extends Model
{
    public function orders()
    {
        return $this->hasMany(Order::class);
    }
}
Sample Program

This Author model has many Book models. When you get an author, you can list all their books easily.

Laravel
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Author extends Model
{
    public function books()
    {
        return $this->hasMany(Book::class);
    }
}

// Usage example in a controller or tinker:
$author = Author::find(1);
foreach ($author->books as $book) {
    echo $book->title . "\n";
}
OutputSuccess
Important Notes

Make sure your related table has a foreign key column named like author_id by default.

You can customize the foreign key and local key by passing extra arguments to hasMany().

Summary

One-to-many connects one model to many related models.

Define a method returning hasMany() in the main model.

Use it to easily access all related items for one record.