How can I mock a different model to retrieve a polymorphic relationship?

Posted 1 week ago by chrislentz

I have 3 data models, one of which extends the other:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Opinion extends Model
{
    public function reactions()
    {
        return $this->morphMany('App\Models\Reaction', 'reactable');
    }

    ...
}
namespace App\Models\Activity;

use App\Models\Opinion;

class ActivityOpinion extends Opinion
{
    ...
}
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Reaction extends Model
{
    public function reactable()
    {
        return $this->morphTo();
    }

    ...
}

The App\Models\Opinion model has a polymorphic relationship with the App\Models\Reaction model. I can retrieve all of the App\Models\Opinion reactions no problem, so I know the relationship works great.

My question is, how can I retrieve the same set of reactions from the App\Models\Activity\ActivityOpinion model? Because right now, it is looking for App\Models\Activity\ActivityOpinion as the relationship but I need it to look for App\Models\Opinion. Is it possible to mock another model in a polymorphic relationship?

I have tried messing with morphMap which I am already using in the project for another area, but I can't assign 2 different models to a single key in the morphMap.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.