Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Jakub003's avatar

Filtering results with has many relationship

I am not sure what this would be called, so any insight would be much appreciated so I can possibly find this in the laravel docs

I am trying to create a filter button, where you can click on the User Icon and it would show all the cards where that user has been assigned to the card. I was able to do this with tags, but that was kind of easier since a card can have one tag, but not sure how to do this with users since it can have many.

Project Card can have many users

public function users(){
        return $this->hasMany('App\Models\ProjectCardUser','card_id');
    }

Project Card belongs to User

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

Filtering cards by users

I am not even sure how to wrap my head around this to get started, since need to check the model of ProjectCardUser if the user_id exists there for this card_id

public function filterCardsByUser($user_id)
    {
        $this->cards = ProjectCard::where('kanban_id', $this->kanban->id)
                                        // where if users.user === $user_id ?                          

                                        ->with( 'users',
                                                'files',
                                                'comments',
                                                'comments.user',
                                                'comments.tag',
                                                'tasks',
                                                'tag',
                                        )
                                        ->orderBy('updated_at', 'DESC')
                                        ->get();
    }

Any guidance is apprecaited

0 likes
2 replies
MichalOravec's avatar
Level 75
public function filterCardsByUser($userId)
{
    $this->cards = ProjectCard::with([
            'users', 'files', 'comments', 'comments.user', 
            'comments.tag', 'tasks', 'tag'
        ])
        ->where('kanban_id', $this->kanban->id)
        ->whereHas('users', function ($query) use ($userId) {
            $query->where('user', $userId);
        })
        ->orderByDesc('updated_at')
        ->get();
}

Docs: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence

Or with relationship

public function filterCardsByUser($userId)
{
    $this->cards = $this->kanban->projectCards()->with([
            'users', 'files', 'comments', 'comments.user',
            'comments.tag', 'tasks', 'tag'
        ])
        ->whereHas('users', function ($query) use ($userId) {
            $query->where('user', $userId);
        })
        ->orderByDesc('updated_at')
        ->get();
}
1 like
Jakub003's avatar

Thank you so much for the help and link to docs :)

Please or to participate in this conversation.