I have a category table with category id, name and parent_id and I have a product table having a column category_id that stores multiple category id like ["1", "2", "4"].
Now I'm having a problem in getting product details from the product table which has an id column.
$category = Category::where('slug', $this->catslug)->get()->first();
$data = array();
foreach($category as $cat){
$data['category'] = $cat->id;
$data['products'] = DB::table('products')
->whereJsonContains('category_id', json_decode($cat->id))
->inRandomOrder()->limit(8)->get();
}
dd($data);
My Answer:
You can try the following code to get products based on the category id:
php
$category = Category::where('slug', $this->catslug)->first();
$data = array();
$data['category'] = $category->id;
$data['products'] = Product::whereJsonContains('category_id', $category->id)
->inRandomOrder()
->limit(8)
->get();
dd($data);
In this code snippet, we are fetching the category based on the slug, then getting the products where the category_id column contains the category id. We are then ordering the results randomly and limiting it to 8 products. Finally, we are dumping the data to see the results.
Rate this post
4 of 5 based on 8568 votesComments