Home > Software engineering >  Outputting an array of categories
Outputting an array of categories

Time:10-13

On my page there is a choice of categories and, accordingly, the output of articles that are in the categories.

This is how it goes

<div class="blog-filter">
  <div class="blog-filter__item active" data-filter="all" value="All ({{ $allArticlesCount }})">
    All ({{ $allArticlesCount }})
  </div>
  @foreach ($categories as $category)
    <div class="blog-filter__item" data-filter=".category_{{ $category->id }}" value="{{ $category->title }} ({{ $category->articles_count }})">
      {{ $category->title }} ({{ $category->articles_count }})
    </div>
  @endforeach
</div>

<div class="blog-list">
  @foreach($articles as $article)
    <div class="blog-article category_{{ $article->blog_category_id }}"
      <h2 class="blog-article__title">{{ $article->title }}</h2>
      <span>{{ date('d F Y', strtotime($article->published_at)) }}</span>
    </div>
  @endforeach
</div>

The problem is that I have one category category_{{ $article->blog_category_id }} for each article, and I recently made it possible to add multiple categories for an article. This is how it's done

$article = Article::where('id', $request->article_id)->first();

$blog_categories_ids = json_decode($request->blog_categories_ids);

$article->blog_categories()->detach();

$blog_categories_ids = BlogCategory::whereIn('id', $blog_categories_ids)->pluck('id')->toArray();

$article->blog_categories()->attach($blog_categories_ids);

return response()->json([
    'message' => $blog_categories_ids
], 200);

And I also have a new many-to-many relationship and there is no blog_category_id field in the article now.

The question is, how can I display multiple categories in one article?

CodePudding user response:

In your php, the following lines

$article->blog_categories()->detach();

$blog_categories_ids = BlogCategory::whereIn('id', $blog_categories_ids)->pluck('id')->toArray();

$article->blog_categories()->attach($blog_categories_ids);

can be replaced by just

$article->blog_categories()->sync($blog_categories_ids);

To show all the categories, simply loop through them. Here's an example.

<h1>Article Title: {{ $article->title }}</h1>
<h2>Article Categories:</h2>
<ul>
  @foreach ($article->blog_categories as $category)
    <li>{{ $category->name }}</li>
  @endforeach
</ul>

If you want to show every blog category's name. Maybe you can even use the collection's implode method to achieve it.

<h1>{{ $article->title }}<br><small>{{ $article->blog_categories->implode('name', ', ') }}</small></h1>
  • Related