1 month ago

Where clause in Polymorphic Relationship

Posted 1 month ago by pickab00

I have 2 tables. 1 is the polymorphic table and the other is a simple posts table. Here:


 - id
 - title
 - detail


 - uuid
 - viewable_type
 - viewable_id

and in my model:


public function views() {
      return $this->morphMany(Viewable::class, 'viewable');


public function viewable() {
        return $this->morphTo();

So now I want to get the total count of the items and I am doing this (which works):

$post = Post::find(1);
$post->views()->count(); //which works as expected

What I want to do is to check the UUID and check if the UUID exists in the table. Here is what I tried:

$post->whereHas('views', function($q) {
	$q->where('uuid', 'someuuid')

This does not seem to work. And also, I want to take unique items only. So suppose the UUID is repeated in the table. I want to ignore the repeated and if the UUID exists, I want the count of that record as 1 (excluding the repeats)

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