php – Laravel 5无法将变量传递给所有视图

将变量(数据)传递给所有视图时遇到问题.我创建了扩展认Laravel控制器的BaseController,并在那里定义了“全局”变量.当我使用BaseController扩展其他控制器时,我得到错误,即未定义变量.有谁知道问题出在哪里?

这是代码

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Sentry;
use Illuminate\Http\Request;
use View;

class BaseController extends Controller {
    public function __construct() {
        $obavijesti="Other data";
        $izbornici="Some data";
        View::share ( 'izbornici', $izbornici );
        View::share ( 'obavjesti', $obavjesti );
        }
   }

class AdminController extends BaseController {
     .
     .
     .
      echo '<pre>';var_dump($izbornici);echo '</pre>';//Error pop ups here

     .
     .
     .
}

解决方法:

你这里做错了什么. view :: share()用于跨所有视图而不是控制器共享一段数据.

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Sentry;
use Illuminate\Http\Request;
use View;

//If you wish to get these variables in your other controllers you do this:

class BaseController extends Controller {

    public $obavijesti="Other data";
    public $izbornici="Some data";

    public function __construct() {
       View::share ( 'izbornici', $this->izbornici );
       View::share ( 'obavjesti', $this->obavjesti );
    }  

}

class AdminController extends BaseController {

    //if you have a constructor in other controllers you need call constructor of parent controller (i.e. BaseController) like so:

    public function __construct(){
       parent::__construct();
    }

    public function Index(){
      echo $this->obavijesti;
    }

}

您还可以使用composer将变量共享给视图

//1. Create a composer file at app\Composers\AdminComposer.PHP
//NB: create "app\Composers" if does not exists

//2. Inside AdminComposer.PHP add this.


<?PHP namespace App\Composers;

class AdminComposer
{
    public function __construct()
    {

    }

    public function compose($view)
    {
        //Add your variables
        $view->with('izbornici',      'Other data')
            ->with('obavjesti',       'Some other data');
    }
}

//3. In you controller do this:

<?PHP namespace App\Http\Controllers;
//NB: I removed your BaseController because I believe the issue is coming from //there

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Sentry;
use Illuminate\Http\Request;
use View;

class AdminController extends Controller{


    public function __construct(){
        //Lets use AdminComposer to share variables to adminpage.blade.PHP view

        View::composers([
            'App\Composers\AdminComposer'  => array('adminpage')
        ]);

    }

    public function Index(){
        return view('adminpage');
    }

}

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...