On the SitePoint PHP blog there's a new post from Younes Rafie looking at polymorphic relationships and how they're used in the Laravel Eloquent functionality to relate tables and entities to one another.
While I was working on an application for a client, I had to implement a new module that entails the following:
- Users ask for a budget quotation for a certain task.
- Every task has a location.
- Professionals can subscribe to different zones.
- A zone can be a region or a city.
Now, let’s neglect the core application and try to implement this single module to see what we can achieve here.
He starts off by scaffolding out a basic Laravel application, setting up the database configuration and creating the migrations for "Zones", "Regions" and "Cities". He looks a bit more in-depth at how the models were created and how to create the methods relating one to another. The relation goes "through" the zones handling, so they use the "morphedByMany" and "morphedMany" to tell Eloquent how to make the connection. He then shows how to use the relations in your code and some of the collection helper methods to make it simpler to get just the data you want.