Search code examples
phpeloquentlaravel-5.5

Laravel eloquent relationship polymorph multidata notworking


As a title, I'm trying to get a name of the data using polymorph relationship.

When I get a single object its work perfect. but when result multiple objects it's not.

here my try.

>>> $page = App\PageAtribut::first()
=> App\PageAtribut {#2863
     id: 1,
     page_id: 1,
     watchable_id: 1,
     watchable_type: "App\Category",
     created_at: "2018-09-11 11:03:20",
     updated_at: "2018-09-11 11:03:20",
   }
>>> $page->watchable
=> App\Category {#2857
     id: 1,
     name: "Series",
     created_at: "2018-09-11 11:01:46",
     updated_at: "2018-09-11 11:01:46",
   }

on the code above its working. since I use an 'id' to get the data.

next, I try to get all the data using condition page_id equal a page id.

>>> $page = App\PageAtribut::where('page_id', 1)->get()
=> Illuminate\Database\Eloquent\Collection {#2859
     all: [
       App\PageAtribut {#2860
         id: 1,
         page_id: 1,
         watchable_id: 1,
         watchable_type: "App\Category",
         created_at: "2018-09-11 11:03:20",
         updated_at: "2018-09-11 11:03:20",
       },
       App\PageAtribut {#2861
         id: 2,
         page_id: 1,
         watchable_id: 2,
         watchable_type: "App\User",
         created_at: "2018-09-11 11:03:40",
         updated_at: "2018-09-11 11:03:40",
       },
     ],
   }
>>> $page->watchable
Exception with message 'Property [watchable] does not exist on this collection instance.'

and here the result.

Exception with message 'Property [watchable] does not exist on this collection instance.'

how to get the name if there more than one object like above?...


Solution

  • mentioned on @Jigar comment and @Adlan Answer.

    Because get returns a collection and first returns a single model instance.

    Since its array collections its need to use forloop to get attribute on every model.

    so the code would be.

    $page = App\PageAtribut::where('page_id', 1)->get()
    

    then

    foreach($page->pageatribut  as $p)
    { 
        echo $p->watchable->name; 
    }
    

    its return all the name every collection.

    CMIIW.