How can i get types of a morph in Polymorphic many to many relationship in Laravel

  eloquent, laravel, laravel-8

I have three tables – Medias, Cities and Genres. The relationship between them is Many To Many (Polymorphic). A City has many Medias, A Genre also has many medias and vise versa.

Cities
  id, name

Genres
  id, name

Medias
  id, name

Mediaable
  id, mediaable_id, mediaable_type

I want to get all Medias with theirs mediaable types :

  #items: array:3 [▼
    0 => AppModelsMedia {#1128 ▼
         [
       "id" => 1,
       'name'=>'foo.png',
       "types" => ['City', 'Genre']
  ],

   1 => AppModelsMedia {#1128 ▼
        [
       "id" => 1,
       'name'=>'foo.png',
       "types" => ['City']
   ],

    2 => AppModelsMedia {#1128 ▼
        [
       "id" => 1,
       'name'=>'foo.png',
       "types" => []
   ],
];

How can I do that?

Source: Laravel

Leave a Reply