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

zizi_ove's avatar

Laravel Many to Many Polymorphic Query

Suppose we have many to many polymorphic relationship same like Laravel documentation:

    posts
        id - integer
        name - string
    
    videos
        id - integer
        name - string
    
    tags
        id - integer
        name - string
    
    taggables
        tag_id - integer
        taggable_id - integer
        taggable_type - string

The main question is, how to check the existence of a specific record in taggables table if I have tag_id and taggable_id and taggable_type. How can I write this query?

Already I always make a model for taggables table in Laravel and find the specific record but I think this is not the right solution.

Any help will be appreciated, Thank you.

0 likes
2 replies
James_Moore's avatar
Level 14

Hey @zizi_ove this seems like the solution your looking for. It shows examples for a 'Laravel-ish' way and a nice simple query builder way.

https://stackoverflow.com/questions/24555697/check-if-belongstomany-relation-exists-laravel

The second example of using query builder seems very straight forward. So you would create a route and controller, pass the tag_id and taggable_id as request parameters and then use them in the where clause.

1 like

Please or to participate in this conversation.