In this episode, we dive into one of the most common relationship types you'll use in Laravel: the one-to-many relationship. We use a typical example — a user having many posts — and walk through how to set this up in a Laravel app, starting right from our routes file, much like we did with one-to-one relationships earlier.
We start by making a fresh Laravel project (database all set up, but nothing migrated yet), and then together we run our migrations. First, we clear out the default welcome view and get ready to define the actual relationship in the database. This means creating a Post
model (with a migration) and setting up that all-important foreign key linking posts back to users. It's pretty similar to a one-to-one setup, but the real difference is in how we access the data.
Next, we run our migrations to create the tables and use Laravel's factory and Tinker to create a fake user. Then, we open up the User model and add a posts()
method that uses Laravel's hasMany
relationship. It's actually really simple — just a single line specifies that a user can have many posts.
To check our work, we head over to the routes file, grab the user, and access their posts relationship. Notice: when we access it, Laravel gives us a collection (not just a single model like in a one-to-one) — perfect since a user can have lots of posts. We briefly touch on how collections work in Laravel (like how you'll usually just loop over them), but we'll dig into them more later on.
This episode is all about seeing how easy Laravel makes it to set up and use one-to-many relationships — and why it's such a fundamental building block for most apps. By the end, you’ll see just how little code it takes to get this super useful pattern working.