Search code examples
phplaraveleloquentmodelsrelationships

Laravel - How to add where statement within related table and parent table at the same time?


I have two tables: members (userdata, email, etc) and users (username, password, etc). All users are members but not all members are users. I defined the relationship in laravel:

Member.php

public function user() {
    return $this->hasOne('App\Models\User');
}

Now I want to be able to retrieve a member's data either by email or by username (if it exists) without using join(). Basically:

where('email','=','blah123')->orWhere('username','=','blah123')

I want the relationships returned in their own arrays like:

{
    firstname: blah,
    email: [email protected],
    user: [
        username: blah123
    ]
}

And when I use join() it returns a flat array which is not ideal:

{
    firstname: blah,
    email: [email protected],
    username: blah123
}

How would I go about it?


Solution

  • Try this:

    where('email','=','blah123')->orWhereHas('user', function($query) { 
        $query->where('username','=','blah123');
    })->with('user')