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.