'Fetch specific data for Auth user from Many to Many Relationship in Laravel

How do I fetch data for specific authenticated user in a Laravel many-to-many relationship? I have a page where it will display all the latest threads from all communities. However, I want to make sure it will only show the threads from a community where the currently login user belongs to. (I'm not sure if I made sense)

User.php

public function communities()
{
    return $this->belongsToMany(Community::class)->withTimestamps();
}

public function threads()
{
    return $this->hasMany(Thread::class);
}

Community.php

public function users()
{
    return $this->belongsToMany(User::class)->withTimestamps();
}

public function threads()
{
    return $this->hasMany(Thread::class);
}

Thread.php

public function user()
{
    return $this->belongsTo(User::class, 'author_id', 'id');
}

public function community()
{
    return $this->belongsTo(Community::class);
}

This is how I fetched the data with no logged in user.

$threads = Thread::with(['user', 'community'])->orderBy('created_at')->paginate(20);

What I want to achieve is to get the latest threads from communities where the logged in user belongs to.



Solution 1:[1]

You can use auth to access to authenticated user, there are two ways to using it, First use auth directly and second use Auth Facade:

  1. Directly

    $threads = auth()->users()->threads()

  2. Facade

    $threads = Auth::user()->threads()

Solution 2:[2]

To get the currently logged in user, we can use the auth()->user() helper function and get the communities like the following:

$communities = auth()->user()->communities;

But you need the threads of those communities, so we must add in more logic where we fetch the IDs of those communities you follow, then retrieve all the threads that those communities contain to then perform whatever queries you need at the end.

$communityIds = auth()->user()->communities->pluck('id');
$threads = Thread::whereIn('community_id', $communityIds)->latest()->paginate(20);

I haven't tested this code since I don't have the same structure, so you may need to debug a thing or two to fix the queries but it should theoretically perfectly match your structure.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ahmad
Solution 2