尝试将数据传递给视图时未定义的变量 - Laravel 5

Undefined variable when trying to pass data to the view - Laravel 5

我试图在我的所有页面上包含一个视图(代码在下面),所以我将它包含在我的布局模板中(因此它呈现在所有页面上)。不幸的是,当我尝试 运行 任何页面时 - 出现此错误:

Undefined variable: sites (View: /Users/Documents/audit/resources/views/layouts/check.blade.php)

查看 (check.blade.php):

@if (count($sites) == 0)
 // Removed as it is irrelevant.
@endif

控制器:

public function siteCheck()
{
  return View::make('layouts.check')
                  ->with('sites', Site::where('user_id', Auth::id())
                  ->get());
}

我尝试包含视图(显示错误)的地方:

@if(!Auth::guest())
  @include('layouts.check')
@endif

N.B。我没有在路由中添加与 layouts.check 页面相关的任何代码。

非常感谢您的帮助。

试试这个

@if(isset($sites)&&count($sites) == 0)
 // Removed as it is irrelevant.
@endif

注意:

当你使用 @include('layouts.check') 时你没有设置 $sites

问题是当您包含文件时 layouts.check 方法 siteCheck() 没有启动(因此变量 $sites 不存在)。

您有两个选择:

  1. 在包含文件时添加一个变量

@include('layouts.check', ['sites' => $sites]) (您仍然需要从主视图的控制器传递 $sites。)

  1. 添加视图编辑器,每次包含视图时添加此变量

参见:https://laravel.com/docs/5.2/views#view-composers

在你的情况下它看起来像这样:

public function boot()
{
    view()->composer('layouts.check', function ($view) {

        $view->with('sites', Site::where('user_id', Auth::id())
              ->get());
    });
}