Answer the question
In order to leave comments, you need to log in
How to display in Laravel - the number of users from a certain category?
How to display in Laravel - the number of users from a certain category?
So we display the total number: $users = DB::table('users')->count();
In the database, in the users table, there is a category_id
category_id = 2 - such and such users
Answer the question
In order to leave comments, you need to log in
This is the third question on this topic.
In your case, you have implemented One-to-many, that is, 1 category => many users.
Set up relationships and write queries
// User.php
public function category()
{
return $this->belongsTo(Category::class);
}
// Category.php
public function users()
{
return $this->hasMany(User::class);
}
// в контроллере получаем категории и кол-во пользователей
$categories = Category::withCount('users')->get();
// кол-во определенных пользователей
$categories = Category::withCount(['users' => function($query) {
$query->where('active', 1);
}])->get();
// доступ во вьшке
@foreach($categories as $category)
{{ $category->users_count }}
@endforeach
$users = DB::table('users')->where("category_id", "=", 2)->count();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question