Polymorphic many to many relation in laravel

  laravel, polymorphic-relationship

First time I used polymorphic many to many relation in LARAVEL 5.1 but somehow it doesn’t work I attach my code can you find out what I do wrong?

Tables

users table

 id | name | email
 -------------------------
 1 | john | [email protected]
 --------------------------
 2 | adam | [email protected]

companies table

id | name | email
-----------------
 1 | tesla | [email protected]

calendar_subscriptions table

id | user_id | resourceable_type | resourceable_id
--------------------------------------------------
 1 | 1       | AppModelsUser   | 2
--------------------------------------------------
 2 | 1       | AppModelsCompany | 1

CalendarSubscription Model

 class CalendarSubscription extends Model
 {
   protected $table = 'calendar_subscriptions';


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

 }

User Model

class User extends Model {

 public function calendarSubscription()
 {
    return $this->morphMany('AppModelsCalendarSubscription','resourceable');
 }
}

Tried

  User::with('calendarSubscription')->where('id', '=', Auth::user()->id)->get();

Problem
It does not return these name adam and tesla

Want below data in collection form

 id | name | email
 -------------------------
 1 | john | [email protected]
 --------------------------
 2 | adam | [email protected]
 --------------------------
 1 | tesla | [email protected]

First Fetch all the details from calendar_subscriptions where user_id = 1 then get
the name of company and user.

I know project structure is wrong. I could not change anything and must follow this structure

Source: Laravel

Leave a Reply