Laravel 4 – Pivot vs Polymorphic – Part 1

Laravel Logo

Laravel Logo

PHP has come a long way! Coming from the Rails world back to PHP has actually been pretty painless thanks to Laravel. One of the first things that stumped me was under what circumstances to use pivot vs polymorphic relationships. This post is more of a reminder for myself but I hope it clarifies things for anyone wondering the same thing. I will outline below two examples, one using a pivot and one using a polymorphic relationship.

(Side note: I’m still a happy rails dev and promise to post more on that later.)

Before we get started. Here is what you need:



A perfect example of a polymorphic relationship is comments. It’s a pretty universal thing – you might want comments on a blog post, pages, or even specific items in your website. However, you don’t necessarily want to create a new table for each item that allows comments. This is where the polymorphic stuff comes into play and makes your life easier.

tldr link to project:

To keep it simple, we’re going to have two main models “BookLibrary” and “Books”. Ideally, each book could belong to many libraries but in this simple example, we’re going to assume each book belongs to a specific library. The focus of this project will be to allow you to comment on either model using one “Comment” model.

Let’s get started…

BookLibrary Migration

Book Migration

Comment Migration

Migrate your tables using the “php artisan migrate” command. Next up is setting up our models. I’m using the way generators (linked above). Make sure you read up on it, huge time saver.

BookLibrary Model

Book Model

Comment Model

That’s all there is to it! You should see a pattern here. Any model we want to be able to add comments to, we simply add the morphMany relationship and you’re all set. Laravel takes care of the rest. Here are a few examples to get you started working with polymorphic relationships in Laravel.

I’ll be using “php artisan tinker” command to setup data and some examples.

Simple right? Stay tuned for part 2 of this blog where we cover pivot relationships. Comment below with any questions!

, , , , ,