Video Course

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:

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

Chris Sevilleja

156 posts

Co-founder of Scotch.io. Slapping the keyboard until something good happens.