2016-01-21 63 views
1

在每個菜單項中,我需要顯示裏面包含的項目數。例如:在laravel 5.1中的每個模型中獲取元素數量的優雅方式5.1

Users (22) 
Posts (57) 
Categories (14) 
Cities (92) 

試圖做這樣的事情:

應用/搜索/作曲/ 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(), 
    ]); 
    } 
} 

應用/供應商/ 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 

但它看起來像一個笨拙的,因爲模型可能更多。
請幫助找到更美觀的解決方案。

+0

我不完全理解你想做什麼? – haakym

+0

我需要傳遞給menu.blade.php包含在每個模型中的行數 –

回答

2

我不知道我完全理解你,但我給它一個去

// in controller 
// change with your models location 
$model_files = \File::allFiles('../app/models'); 

foreach($model_files as $model_file) 
{ 
    $pos = strrpos($model_file->getRelativePathname(), "."); 
    // add your 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 as $model) 
     <li class="menu-item">{{ $model }} ({{ $model::count() }})</li> 
    @endforeach 
</ul>