Home > Net >  Fetch specific data for Auth user from Many to Many Relationship in Laravel
Fetch specific data for Auth user from Many to Many Relationship in Laravel

Time:02-16

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.

CodePudding user response:

You should be able to do it as easily as using the auth()->user() helper function:

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

And then perform whatever sorting or pagination you need.

CodePudding user response:

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()

  • Related