B
B
BarneyGumble2020-10-23 22:33:52
Laravel
BarneyGumble, 2020-10-23 22:33:52

How to pull records by tag from PIVOT table in Laravel in controller?

I'm picking this tag package for Laravel - https://github.com/spatie/laravel-tags

I don't understand how to pull records with a specific tag in the controller. Difficulties are precisely in compiling an Eloquent query

. There are three tables:
- Posts
- Tags
- Taggable (PIVOT table connecting tag IDs and record IDs)

5f932e5c83bce092973029.jpeg

$posts = Post::get();
so all records are pulled out

$posts = Post::select(
            'posts.*'
        )
            ->join('taggables', 'posts.id', '=', 'taggables.taggable_id')
            ->get();

I tried this but it doesn't work :(

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2020-10-23
@BarneyGumble

The taggables table is used for polymorphic linking to add tags to any models. Didn't get into this module. But judging by the first line from the description, you need to add the HasTags trait to the Post model. The trait will already contain all relations with methods without prescribing links, etc.
You can get all posts with tags like this

Post::withAnyTags(['first tag', 'second tag'])->get();

although the name of the method is bad and can be confusing. with in Laravel has a different function than whereHas. It would be better to haveAnyTags
ps before adding modules, it will not be superfluous to read why you need a framework, relationships, and why you can no longer use join.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question