R
R
Rodion2018-03-06 10:27:26
Laravel
Rodion, 2018-03-06 10:27:26

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

4 answer(s)
Z
zorca, 2018-03-06
@zorca

Do not forget to read the docs

A
anlamas, 2018-03-06
@anlamas

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

There are Russian-language sites with docks laravel.su and laravel.ru

R
Rodion, 2018-03-06
@azmarin

Some kind of shit (((

M
Maxim Klimenko, 2018-03-11
@maaxim

$users = DB::table('users')->where("category_id", "=", 2)->count();

It seems so, but I think it's better to use ORM)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question