nolros's avatar
Level 23

Easier method to test for Eloquent Collection or instance?

In the case where you are using Eloquent's with relationships ->with() is there an easier way to test if what is returned is an instance of the relationship or a collection. If there is only one record Eloquent will return that as an instance of the model, but if there are more then one you end up with a Collection which makes sense, however, if you a re using dynamic property then you need to test e.g.

    private function groupMembers( $permission )
    {
       // check for instance 
        if ($permission->groups->members instanceof SecurityGroupMember)
        {
            $this->members->push( $permission->groups->members) ;
        }
        // check for Collection
        if ($permission->groups->members instanceof Collection)
        {
            foreach ($permission->groups->members as $member)
            {
                $this->members->push( $member );
            }
        }
        return $this;
    }
0 likes
1 reply
SachinAgarwal's avatar

@nolros If the relation is "one to may" or "Many to Many" you will always get collection with get() even if it is only one record.

Please or to participate in this conversation.