Laravel Eloquent Relationships: Lesson 3 of 7

One to Many

Up Next

One to Many Tips

Autoplaying in 7 seconds!

Cancel

To define a one to many relationship, the database setup is the same as one-to-one relationships. Make sure that one of the tables has a key that references the id of the other table.

For example, a posts table will have a field called user_id. That will reference the users.id field. Eloquent will handle the rest.

// app/User.php

...

public function posts() {
    return $this->hasMany('App\Post');
}

...

To save a one-to-many relationship:

Table of Contents

    $user->posts()->saveMany($posts);

    Chris Sevilleja

    176 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.