ManyToMany Relationship With Third Table


Using Laravel 5.5

I am trying to design an incident management system which has bespoke requirements. In short, we have the following:

  1. Various Platforms
  2. Various Contact Groups
  3. Various Priorities

The platforms table and priorities table has a ManyToMany relationship, and I now have the intermediary table 'platform_priority'. The reason it has been done this way is because we require different contact groups for each platform and priority assignment.

We would create a platform, assign the priorities that can be used for that platform, and then the idea is to be able to assign the contact groups to each priority on the platform management page.

Table structure is as follows:

PLATFORMS: id name


PLATFORM_PRIORITY: id platform_id priority_id contactgroup_id

The problem is, I want to get the value of 'contactgroup_id' and pull/display the name column that matches this ID of the contact group in the view.

How would I go about doing this?


Alberto Rosas replied 9 months ago

First of all you would have to create the relationships between those tables in each class:

// Declare relationships in both models

    class Platform extends Model {

        public function priorities() {
            return $this->belongsToMany(Priorities::class);


    class Priority extends Model {

        public function platforms() {
            return $this->belongsToMany(Platform::class);


// Now in your controller you would have to retrieve the value:

    public function getPlatformName($platform_id) {

        $platforms = App\Platform::findOrFail($platform_id);

        foreach($platform->priorities as $priority) {
           echo $priority->name;


// otherExample

    $priorities = App\Platform::findOrFail($platform_id)->priorities()->orderBy('name')->get();

    foreach($priorities as $priority) {
       echo $priority->name;

// Hope its clear enough, for better understanding go to:

Good Luck bro!

Sign in to participate in this thread!

We'd like to thank these amazing companies for supporting us