如何在 laravel 中的 foreach 中显示博客类别?

How to show weblog categories in foreach in laravel?

我的网站有一个类别和博客。

这是类别模型:

public function weblogs()
{
    return $this->belongsToMany(Weblog::class);
}

这是博客模型:

public function categories()
{
    return $this->belongsToMany(Category::class);
}

如您所见,Weblog 和 Category 之间存在关联。

这是控制器:

$weblogs = Weblog::paginate(9);
return view('index', compact('weblogs'));

这是我用来显示博客项目的 blade :

@foreach($weblogs as $weblog)
            <div class="col-lg-4 col-sm-6">
                <div class="blog-item">
                    <div class="thumbnail">
                        <a href="#"><img alt=""
                                         src="/Weblog/image/{{ $weblog->image }}"></a>
                    </div>
                    <h4><a href="#">{{ $weblog->name }}</a></h4>
                    <ul>
                        <li><a href="#">{{ jdate($weblog->created_at)->format('%d %B %Y') }}</a></li>
                        <li><a href="#">سبک زندگی</a></li>
                    </ul>
                    <div class="blog-btn">
                        <a href="#" class="btn-st">بیشتر بخوانید</a>
                    </div>
                </div>
            </div>
@endforeach

我想显示属于任何博客项目的类别,我该怎么做?

只需在您的模板中访问 属性

<div class="blog-item">
    ...
    @foreach ($weblog->categories as $category)
      {{ $category }}
    @endforeach
    ...
</div>

您也可以提前加载关系

$weblogs = Weblogs::with('categories')->paginate(9)

您可以在此处阅读更多相关信息 https://laravel.com/docs/7.x/eloquent-relationships#relationship-methods-vs-dynamic-properties and here https://laravel.com/docs/7.x/eloquent-relationships#eager-loading