Search code examples
laravelmodel-view-controllersidebarlaravel-8

Show record counts in sidebar in laravel 8


I am writing a project in Laravel 8. I want to show the number of each menu in the left menu. Actually I have a solution. Adding other models to all controls on the site. But this is not the right way. Is there an alternative to this?

For example:

My sidebar menus:
Tools (12)
Users (10)
Settings

I need to insert this code to all controls functions

$tools_1= Tools1::all()->count();
$users = Users::all()->count();

I am also write this code to the sidebar.

          <li class="nav-item">
            <a href="{{route('admin.x')}}" class="nav-link">
              <i class="nav-icon fas fa-warehouse"></i>
              <p>
                Tools
                <span class="badge badge-info right">{{ $tools_1 }}</span>
              </p>
            </a>
          </li>
          <li class="nav-item">
            <a href="{{route('admin.y')}}" class="nav-link">
              <i class="nav-icon fa fa-car"></i>
              <p>
                Users
                <span class="badge badge-info right">{{ $users }}</span>
              </p>
            </a>
          </li>

Is there a more logical solution?


Solution

  • You can move the sidebar markup to a partial - say sidebar.blade.php

    Then use a view composer to pass data to the sidebar. Register the View composer in the boot method of a service provider - even AppServiceProvider is okay.

    Use caching in the view composer for performance boost and limiting database queries

    //In the boot method of service provider
    View::composer('sidebar', function ($view) {
        $counts = Cache::remember('counts', 3600, function() {
            return [ 'tools_1' => Tools1::count(), 'users' => User::count() ];
        });
    
        return $view->with('counts', $counts);
    });
    
    //OR you can use a wildcard to share data with multiple views
    View::composer('admin.*', function ($view) {
        $counts = Cache::remember('counts', 3600, function() {
            return [ 'tools_1' => Tools1::count(), 'users' => User::count() ];
        });
    
        return $view->with('counts', $counts);
    });
    

    Laravel docs:

    Then in the partial you can use the data passed via view composer

    <span class="badge badge-info right">{{ $counts['users'] }}</span>
    <span class="badge badge-info right">{{ $counts['tools_1'] }}</span>