N
N
NikSIk312019-08-14 02:19:27
Laravel
NikSIk31, 2019-08-14 02:19:27

Laravel display by subscriptions?

There is a table, so to speak, with tags to which the user is subscribed. (For example: nature, science)
And another table of posts where there is a post with all sorts of things and one tag. You need to get all posts with tags that the user is subscribed to.
--- Now I have the following solution in my head:
I get a list of tags like Tag::where("user_id", Auth::user()->id)->get(); then you probably need to convert to an array and somehow get Post::select("name")->whereIn($tags)->get(); this is how it comes to my mind. Can you criticize / or suggest a better solution?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jazzus, 2019-08-14
@jazzus

Why with one tag? So that the spam tag is not moderated?) It is better to make initially as many tags as you like and limit it with application settings so as not to refactor the database structure later. On this topic. You need to associate users with tags, and tags with posts through manyToMany type

public function tags()
{
  return $this->belongsToMany('как в доках');
}

and request
$user = User::with('tags.posts')
            ->find(Auth::id());

there will be a user with a collection of tags, and each tag will have a collection of posts. in the template you can type like this
@foreach ($user->tags as $tag)
  @foreach ($tag->posts as $post)
    {{ $post->name }}
  @endforeach
@endforeach

How to get user tag posts immediately. In Tag we make a scope
public function scopeOfUser($query, $userId)
{
   return $query->whereHas('users', function($query) use($userId) {
                $query->where('user_tag.user_id',$userId);
          });
}

And the request itself
$posts = Post::with('tags')
             ->whereHas('tags', function($query) use($userId) {
                   $query->ofUser($userId);
               })->get();

Or make polymorphic relations , I didn’t work on it, but maybe they will do here.

N
NubasLol, 2019-08-14
@NubasLol

Here is how to get ids, your solution is ok

$ids = Tag::where("user_id", Auth::user()->id)->pluck('id')
 Post::select("name")->whereIn($ids)->get()

Well, or make a Has One Through relationship
https://laravel.com/docs/5.8/eloquent-relationship...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question