enginerd's avatar

Testing for existence of relational data

I've been doing this for a long time in my transformers:

    public function transform($user)
    {
        $data = [
            'id'                   => (integer)$user['id'],
            'name_first'           => $user['name_first'],
            'name_middle'          => $user['name_middle'],
            'name_last'            => $user['name_last'],
        ];

        if (isset($user->emails)) {
            $tf = new UserEmailTransformer();
            $data['emails'] = $tf->transformCollection($user->emails->all());
        }

        return $data;
    }

but the isset($user->emails) line no longer behaves the same way after updating from 5.2.29 to 5.2.45 or 5.3.*. In a nutshell, it used to only run the object through the UserEmailTransformer when the user specifically asked for emails by ultimately running $query->with('emails'), but now it lazy loads the associated emails objects in the transformer right when it hits that line.

I'm simply trying to check if the emails were queried so I can run them through a transformer and, if not, skip that section of code. I can't find anything in the changelogs that would explain this behavior change and I don't know how to do it to make it work unless I don't update Laravel at all. Any help would be greatly appreciated.

0 likes
3 replies
tamat's avatar

Maybe, you can try is_null($user->emails)

enginerd's avatar

tamat - thanks for the suggestion. I tried is_null and had the same results.

Ahhhh relationLoaded is amazing and exactly what I needed. I'm going to post that all over StackOverflow with credit given to you because no one has mentioned that in any of the questions related to this problem. Thanks!

Please or to participate in this conversation.