2015-07-19 25 views
3

我試圖從3天開始學習laravel,並且我遇到了一些問題。Laravel 5如何在我的視圖中正確使用設置變量

在我的數據庫,我有一個表的「設置」,它看起來像:enter image description here

我需要在每個網頁,我加載使用此數據。我做這樣的事情負載在我的視圖中的數據:

public function indexFront() 
{ 
    $posts = $this->blog_gestion->indexFront($this->nbrPages); 
    $links = str_replace('/?', '?', $posts->render()); 


    //Here i load my setting 
    $setting_gestion = new SettingRepository(new setting()); 
    $config = $setting_gestion->getSettings('ferulim'); 


    //Next i pass my setting to my view 
    return view('front.blog.index', compact('posts', 'links', 'config')); 
} 

它的工作原理,但我需要做的是,在每一個控制器和每一個功能...我覺得有些是另一種方式做同樣的事情: p

幫幫我!

+2

我認爲你正在尋找[View Composer](http://laravel.com/docs/5.0/views#view-composers)。另請參閱關於*與所有視圖共享數據*的部分。 – Quasdunk

+0

好,嫁給我吧! –

+0

不知道如果我的妻子會這樣:) – Quasdunk

回答

2

使用View Composer(http://laravel.com/docs/5.0/views#view-composers),您可以輕鬆實現所選視圖或所有視圖。

首先,你需要實現確實要對每個視圖做邏輯視圖作曲:

<?php namespace App\Providers; 

use View; 
use Illuminate\Support\ServiceProvider; 

class ComposerServiceProvider extends ServiceProvider { 
    public function boot() 
    { 
    View::composer('*', function($view) { 
     $blog_gestion = ...; // fetch or instantiate your $blog_gestion object   
     $posts = $blog_gestion->indexFront($this->nbrPages); 
     $links = str_replace('/?', '?', $posts->render()); 

     $setting_gestion = new SettingRepository(new setting()); 
     $config = $setting_gestion->getSettings('ferulim'); 

     $view->with(compact('posts', 'links', 'config')); 
    }); 
    } 

    public function register() 
    { 
    // 
    } 
} 

接下來,註冊您的新服務提供商提供商陣列在配置/ app.php

就是這樣:)讓我知道是否有任何錯別字/錯誤,我沒有機會運行代碼。

+1

謝謝你的回答!它就像一個魅力;) –

相關問題