Laravel get which Categories belong to logged user in ManyToMany

You can query the relationship existence with whereHas to get only the categories which belongs to the authenticated user.

$categories = Category::whereNull('category_id')
    ->whereHas('users', function ($query) {
        $query->where('id', auth()->user()->id);
    })
    ->with([
        'childrenCategories', 
        'users' => function ($query) {
            $query->where('id', auth()->user()->id);
        }
    ])
    ->withCount('posts')
    ->get();

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top