php - Elegant way to get count of elements in each model in laravel 5.1 -
in each menu item need display number of items contained inside. example:
users (22) posts (57) categories (14) cities (92)
tried this:
app/view/composers/addcountofmodels.php:
namespace app\view\composers; use illuminate\view\view; use app\user; use app\post; use app\category; use app\city; class addcountofmodels { public function compose(view $view) { $view->with('count_of', [ 'users' => user::count(), 'posts' => post::count(), 'categories' => category::count(), 'cities' => city::count(), ]); } }
app/providers/appserviceprovider.php:
namespace app\providers; use app\view\composers; use illuminate\support\serviceprovider; class appserviceprovider extends serviceprovider { public function boot() { $this->app['view']->composer('_layouts.backend', composers\addcountofmodels::class); } } ...
menu.blade.php:
@extends('_layouts.backend') @section('menu') <ul class="sidebar-menu"> <li class="header">menu</li> <li class="menu-item">users ({{ $count_of['users'] }})</li> <li class="menu-item">posts ({{ $count_of['posts'] }})</li> <li class="menu-item">categories ({{ $count_of['categories'] }})</li> <li class="menu-item">cities ({{ $count_of['cities'] }})</li> </ul> @endsection
but looks clumsy because models can more.
please find more beautiful solution.
i'm not sure understand you, i'll give go
// in controller // change models location $model_files = \file::allfiles('../app/models'); foreach($model_files $model_file) { $pos = strrpos($model_file->getrelativepathname(), "."); // add path $models[] = 'app\models\\'.substr($model_file->getrelativepathname(), 0, $pos); } return view('layouts.app')->with(compact('models')); // in view <ul class="sidebar-menu"> <li class="header">menu</li> @foreach($models $model) <li class="menu-item">{{ $model }} ({{ $model::count() }})</li> @endforeach </ul>
Comments
Post a Comment