Answer the question
In order to leave comments, you need to log in
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)
$posts = Post::get();
so all records are pulled out
$posts = Post::select(
'posts.*'
)
->join('taggables', 'posts.id', '=', 'taggables.taggable_id')
->get();
Answer the question
In order to leave comments, you need to log in
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();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question