Search code examples
eloquentlaravel-8polymorphic-relationship

Apply where condition to related models in polymorphic relation laravel 8


I am facing an issue in Polymorphic relations where I can not make whereHas to work. The relation code is working fine to return the related models, but need to apply where conditions to the relations of the models connected with the polymorphic relations?

My polymorphic relation is morph mapped by two models. eg: Events and Meetings both models have their own relations to store their assignees (Belongs to many) I need to apply where condition to assignees relation to fetch the required data, In my polymorphic relation, I got the data with assignees but not with the condition applied.

class MainEvant extends Model
{
     public function eventheadable()    
         {  
          return $this->morphTo('eventhead', 'event_type_id', 'event_id')
           ->morphWith([ Events::class=>['assignee'],             
                     Meeting::class=>['assignee'], ]); 
              }

}

Solution

  • I have also faced a similar issue recently, I have solved it by this way, not sure about the quality of the code

    In your Controller ,

     MainEvant::with('eventheadable')->whereHasMorph('eventheadable',Events::class,function ($query)  {
                    $query->whereHas('assignee', function ($q)  {
                        $q->where(); // Your Condition
                    });
                })->orwhereHasMorph('eventheadable',  Meeting::class,function ($query) {
                    $query->whereHas('assignee', function ($q)   {
                        $q->where(); // Your Condition
                    });
                })->get();
    

    Also Check this out in the official doc,

    Docs: https://laravel.com/docs/8.x/eloquent-relationships#querying-morph-to-relationships