Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kacyblack's avatar

Displaying the Total Count of Each Table in Laravel using Eloquent

Am working on a System where the Admin has 3 Tables, Product, User and Staff and What am trying to achieve is this: When the Admin logs in, He sees the Total Count of each Tables Example: Total Product: 89, Total Users: 1098, Total Staff: 564 Please How can I achieve this What Controller Function do I need to Write and How do I pass it to the View? Thanks

0 likes
8 replies
bestmomo's avatar

You just need something like that in controller :

use App\Product, App\User, App\Staff;

...

$productCount = Product::count();
$userCount = User::count();
$staffCount = Staff::count();
return view('myview', compact('productCount', 'userCount', 'staffCount'));
1 like
jlrdw's avatar

bestmomo, I didn't know you could comma separate a compact list like that thanks that's kind of neat.

martinbean's avatar

I personally store counts in an array, so I’m not having to bind many variables to a view. If I want the count from 12 models, I don’t want to be binding 12 variables to my view.

$totals = [
    'articles' => Article::count(),
    'comments' => Comment::count(),
    'events' => Event::count(),
    // And so on
];

return view('admin.dashboard', compact('totals'));
1 like
jlrdw's avatar

@martinbean, a resultset is an array (collection) already, so just curious what difference does that make?

1 like
kacyblack's avatar

@bestmomo Thanks for your Quick replies. I tried what you said in both my Controller and in the route.php in this format

/**
 * admin page
 * @return void
 */
public function userCount()
{

    $productCount = Product::count();
    $userCount = User::count();
    $pinCount = Pin::count();
    
    return View::make('public.pages.admin', compact('productCount', 'userCount', 'pinCount'));
}

THEN ON THE VIEW (Views/public/pages/admin.blade) I echoed $pinCount like this {{ $pinCount }} but I received an error message: Undefined variable: pinCount (View: C:\wamp\www\secureserver\app\views\public\pages\admin.blade.php)

Please what am I doing wrong, Thanks

kacyblack's avatar

This is my Pin Method in (app/models/Pin.php)

class Pin extends Eloquent {

protected $table = 'pins';
protected $guarded = [];

}

martinbean's avatar

@jlrdw I meant array as in if I wanted the counts from multiple models. If I add each model’s count to an array, I just have to bind that single array to my view, rather than a variable per model.

Please or to participate in this conversation.