I've saved the categories as JSON to the database, but I can't just foreach a category on the frontend.
So, for example, I want to show all of the 1 digits in the database with foreach. How can I do it?
Controller:
public function index() {
$contents = DB::table('posts')
->orderByDesc('posts.created_at')
->join('categories', 'posts.categories', 'categories.id')
->whereNull('posts.deleted_at')
->latest('posts.created_at')->get();
return view('frontend.index', compact('contents'));
}
Foreach in Blade:
@foreach($contents->where('status', '1')->where('categories', \DB::table('settings')->first()->design_1)->take(6) as $posts)
<div class="item">
<div class="top-post-wrap top-post-wrap-4">
<div class="thumb">
<div class="overlay"></div>
<img style="object-fit: cover; height: 515px;" src="{{route('frontend.cdn', $posts->img_512)}}" alt="img">
<a class="tag top-right tag-red" href="{{route('frontend.category', $posts->slugname)}}">{{$posts->name}}</a>
</div>
<div class="top-post-details">
<div class="meta">
<div class="date">
<i class="fa fa-clock-o"></i>
{{Carbon\Carbon::parse($posts->created_at)->diffForHumans()}}
</div>
</div>
<h4><a href="{{route('frontend.single', $posts->slug)}}">{{Str::limit($posts->title,70)}}</a>
</h4>
</div>
</div>
</div>
@endforeach
DB "categories" Column in "posts" table:
["1","3","4","5","6","7","8","9","10","11","12","13","14"]
I want to see all posts in category 3 with foreach. For example, there are 3 id numbers in the JSON code I gave as an example.
My Answer:
To achieve this, you can use the `json_decode` function in your controller to decode the JSON string stored in the database and then filter the posts based on the category you want to display. Here's how you can modify your controller and blade file:
Controller:
php
public function index() {
$contents = DB::table('posts')
->orderByDesc('posts.created_at')
->join('categories', 'posts.categories', 'categories.id')
->whereNull('posts.deleted_at')
->latest('posts.created_at')->get();
$category = 3; // Category ID you want to display
$filteredContents = $contents->filter(function ($post) use ($category) {
$categories = json_decode($post->categories);
return in_array($category, $categories);
});
return view('frontend.index', compact('filteredContents'));
}
Blade:
php
@foreach($filteredContents->take(6) as $post)
@endforeach
This code will filter the posts based on the category ID 3 and display only those posts in the frontend. Make sure to adjust the category ID variable according to your requirements.
Rate this post
5 of 5 based on 1312 votesComments