未定义变量:blade laravel 5.6 中的类别

Undefined variable: categories in blade laravel 5.6

我正在尝试在站点地图网页中显示我的类别 这是我的 CategoryController.php

namespace App\Http\Controllers;
use App\Category;
use Illuminate\Http\Request;
class CategoryController extends Controller
{

public function site()
   {
    $categories = Category::all();
    #   return view('template.sitemap', compact('categories'));
    #   return view('template.sitemap',['categories' => $categories]);
     return view('template.sitemap')->with(compact('categories'));
    #   return view('template.sitemap')->withData($categories);
    #   return view('template.sitemap')->with('categories',$categories);
    #   return view('template.sitemap', compact('categories'));
  }
}

我使用的#显示我使用不同的传递变量的方法来查看 我单独使用了每一种方法,但是 none 没有用。

这是模板文件夹中我的站点地图 blade 文件的一部分,我使用类别变量 template.sitempa.blade.php

        <div id="content" class="col-sm-12">
                <h1 class="title"> site map</h1>
                <div class="row">
                    <div class="col-sm-3 hidden-xs hidden-sm sitemap-icon"><i class="fa fa-sitemap"></i></div>
                    <div class="col-md-5 col-sm-6">
                        <ul class="sitemap">
                                <ul>
                                    @foreach($categories as $category)
                                        <li><a href="category.html">{{$category['name']}}</a></li>
                                    @endforeach

                                </ul>
                        </ul>
                    </div>
                </div>
            </div>

我使用了各种获取变量和传递的方法,但是 none 没有用 你有什么建议吗?

试试这个:

public function site()
{
    return view('template.sitemap')->withCategories(Category::all());
}

那么在你看来,做:

dd($categories);

了解您是否正在接收数据。如果没有问题,按需使用:

@foreach($categories as $category)
    <li><a href="category.html">{{$category['name']}}</a></li>
@endforeach

您的 blade 文件应该在目录 template/sitemap.blade.php 中,而不是 template.sitempa.blade.php

public function site()
{
    $categories = Category::all();
    return view('template.sitemap', compact('categories'));
}

@foreach($categories as $category)
    <li><a href="category.html">{{ $category->name }}</a></li>
@endforeach

试试这个

public function site()
{
$this->data['categories'] = Category::all();
return view('template.sitemap',$this->data);
}

可见

@foreach($categories as $category)
<li><a href="category.html">{{$category->name}}</a></li>
@endforeach