TiagoF
TiagoF

Reputation: 63

Laravel Count with where inside blade

I'm trying to get the total comments the user have..

Controller:

public function index()
{
    $setting = Setting::findOrFail(1);

    $comments = Comment::where('published', '=', '1')->get();

    $users = User::all();

    return view('page.index', compact('setting', 'comments', 'users'));
}

View:

@foreach($comments as $comment)

{{ count($users->where('user_id', '=', $comment->user_id)) }}

@endforeach

The problem is that it only returns 0 and i have 2 comments there.. even using the user id to instead of "$comment->user_id" it doesnt work. still display 0.

Upvotes: 1

Views: 5902

Answers (2)

Joseph Silber
Joseph Silber

Reputation: 219938

$users is a collection, not a query. Treat it as such:

@foreach ($comments as $comment)

    {{ $users->where('user_id', $comment->user_id)->count() }}

@endforeach

The collection's where method does not take an operator.


From the wording in your question it seems you actually want it the other way around:

$comments = Comment::wherePublished(1)->get()->groupBy('user_id');

Then in your view:

@foreach ($users as $user)

    {{ $comments->has($user->id) ? count($comments[$user->id]) : 0 }}

@endforeach

Upvotes: 5

The Alpha
The Alpha

Reputation: 146191

I'm late to answer your question and Joseph already showed you the problem but you may also do it differently. You can group comments using Collection::groupBy, for example:

$comments = Comment::all()->groupBy('user_id');

Then in your view you may try this:

@foreach($comments as $user => $userComments)
     // count($userComments)
     // Or
     @foreach($userComments as $comment)
      // {{ $comment->title }}
     @endforeach
@endforeach

In the first loop (@foreach($comments as $user => $userComments)), the $user is the user_id and it's value would be all comments (an array) by this user but in group.

Upvotes: 1

Related Questions