Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mahdizakizadeh's avatar

Call to a member function getRelationExistenceQuery() on null

Hello guys :)

I have 3 different models: User, Student and Teacher And each User has a Student or Teacher profile based on roll its roll field

Well I needed to get details from that profile and I wrote this relation function with if statement:

public function details() {
    if ($this->roll->slug == 'student')
        return $this->hasOne('App\Student');
    else if ($this->roll->slug == 'teacher')
        return $this->hasOne('App\Teacher');
}

It was working well until I need to use whereHas with User in another model that I need to access to details with laravel dot relation

$bills->whereHas('user.details', function($query) use ($name) {
    ...
});

But this time I got an error :(

exception: "Symfony\Component\Debug\Exception\FatalThrowableError"
file: 
 C:\dev\laravel\TadbireNo\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\QueriesRelationships.php"
line: 39
message: "Call to a member function getRelationExistenceQuery() on null"

Please help me guys I'm really stuck! :((

0 likes
2 replies
Cinek's avatar
Cinek
Best Answer
Level 6
if ($this->roll->slug == 'student')
        return $this->hasOne('App\Student');
    else if ($this->roll->slug == 'teacher')
        return $this->hasOne('App\Teacher');

You did not handle the case when roll->slug is different from 'student' and 'teacher'.

mahdizakizadeh's avatar

@Cinek Your answer is correct but whereHas function always return empty collection idk why :( Anyway I completely changed my way

Please or to participate in this conversation.