Polymorphic Eloquent Relationships in Laravel 5

In this post, I would like to show you creating polymorphic relationships in the Laravel5 application. Probable polymorphic relationships are the most advanced eloquent relationships in all available joins in Laravel.

Polymorphic relationships are extremely useful to share same data structure(table) between two or more different types(tables).

Polymorphic Eloquent Relationships in Laravel 5

For Example, let’s assume, we have different types of platforms like New media, video game, Film.. etc.And to hold data of those platforms we have different tables with a different data structure(columns) and each platform has opportunities with the same structure (no change in the table structure of opportunities for all platforms).

In this scenario, we can use Polymorphic relationships instead of creating tables for each type of opportunity. Let’s begin.

First, let me share my tables structure –

First, let’s create Opportunities modal and open the Opportunities model and add the following method:

Let create models for new media, film and video game projects –

// NewMedia.php -new media projects modal

It’s time to begin using the polymorphic relation! The syntax for adding, removing and retrieving opportunities is straightforward; in the following example we’ll attach a new opportunity to a Film project:

You’ll retrieve the list within the controller per usual. Here opportunities are just a collection, so you can easily iterate over it.

If you have other experience or insights using polymorphic relations be sure to share your thoughts in the comments.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun
I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.
DMCA.com Protection Status