Skip to content

Polymorphic Eloquent Relationships in Laravel 5

Last updated on February 17, 2018

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 –

New Media -  id | name | budget | language | country ..etc
Video Game - id | name | graphics | version ..etc
Film - id | name | lead star| director | producer | distribution ..etc

Opportunities - id | name | projecttable_id | projecttable_type | user_id(creator or author)

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

class Opportunities extends Model {

    public function projecttable()
    {
      return $this->morphTo();
    }

}

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

// NewMedia.php -new media projects modal

class NewMedia extends Model {

  public function opportunities()
  {
    return $this->morphMany('\Models\Opportunities ', 'projecttable');
  }

}

// VideoGame.php -Video game projects modal
class VideoGame extends Model {

  public function opportunities()
  {
    return $this->morphMany('\Models\Opportunities', 'projecttable');
  }

}

// Film.php -Film projects modal
class Film extends Model {

  public function opportunities()
  {
    return $this->morphMany('\Models\Opportunities', 'projecttable');
  }

}

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:

$filmProject= Film::find(1);

$opp = new Opportunities();

$opp->name= 'Film Opportunity';
$opp->user_id = Auth::User()->id;

$filmProject->Opportunities()->save($opp);

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

public function index()      
{
  $filmProject= Film::find(1);
  dd($filmProject->opportunities);
}

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments