Search code examples
laravellaravel-7laravel-relations

Morph To Many Laravel relationship


Question.php

public function votes()
{
    return $this->morphToMany('App\User' , 'votable');
}

User.php

public function voteQuestions()
{
    return $this->morphedByMany('App\Answer', 'votable');
}

This shows up:

Call to undefined method Illuminate\Database\Eloquent\Relations\MorphToMany::exits()

And Laravel tells you to:

Did you mean Illuminate\Database\Eloquent\Relations\MorphToMany::get()?


Solution

  • I think something is wrong in your MorphToMany relation. You need something like this:

    Question model:

    public function votes()
    {
        return $this->morphToMany('App\Vote' , 'votable');
    }
    

    Answer model:

    public function votes()
    {
        return $this->morphToMany('App\Vote' , 'votable');
    }
    

    Vote model:

    public function questions()
    {
        return $this->morphedByMany('App\Question' , 'votable');
    }
    
    public function asnwers()
    {
        return $this->morphedByMany('App\Answer' , 'votable');
    }
    

    But if you want to check relation existing, there is has('relationName') method.

    exists() method work only for Eloquent Model instances.