我正在尝试在多个视图上共享变量,所以我尝试了视图编辑器,但由于未传递变量而无法正常工作,并且有任何方法可以对其进行调试
ComposerServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
view()->composer(
'layouts.admin.dashboard',
'App\Http\ViewComposers\StatComposer'
);
}
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
}
所以现在这里是Composer文件
StatComposer.php
<?php
namespace App\Http\ViewComposers;
use Analytics;
use Spatie\Analytics\Period;
use App\Libraries\GoogleAnalytics;
use Illuminate\Http\Request;
use Illuminate\View\View;
class StatComposer
{
/**
* Create a movie composer.
*
* @return void
*/
public function __construct()
{
$result = GoogleAnalytics::topCountries();
$country = $result->pluck('country');
$country_sessions = $result->pluck('sessions');
$topBrowsers = GoogleAnalytics::topBrowsers();
$browser = $topBrowsers->pluck('browser');
$browser_sessions = $topBrowsers->pluck('sessions');
$totalPageViews = GoogleAnalytics::fetchVisitorsAndPageViews();
$date = $totalPageViews->pluck('date');
$visitors = $totalPageViews->pluck('visitors');
$pageViews = $totalPageViews->pluck('pageViews');
}
/**
* Bind data to the view.
*
* @param View $view
* @return void
*/
public function compose(View $view)
{
$view->with('country', 'country_sessions', 'browser', 'browser_sessions','date','visitors','pageViews');
}
}
所以我无法找到调试它的方法,因为变量没有传递给我试图传递给它们的视图,并且该视图给出了未定义变量的错误。
答案 0 :(得分:0)
问题是您声明了很多变量而没有在compose函数中提供值。另外,您实际上并没有将数据保存在任何地方。应该是这样的。
protected $country;
/**
* Create a movie composer.
*
* @return void
*/
public function __construct()
{
$result = GoogleAnalytics::topCountries();
$this->country = $result->pluck('country');
}
/**
* Bind data to the view.
*
* @param View $view
* @return void
*/
public function compose(View $view)
{
$view->with('country', $this->country);
}
请注意,我们在顶部声明了classes属性,然后保存到该属性,然后在with方法中使用$ this-> country属性设置“ country”变量。