Can you use the stackoverflow syntex so we can better read the code ? like
<?php
echo "test";
?>
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have a little query in which I need your help, Please have a look below.
I want to fetch all the data from the products table with some conditions like city, price, Type, category. I can fetch all the data but I can't fetch the category data from the product model with all other conditions.
Below is my tables and Eloquent relations. I am using Laravel 5.2.
products ->foreign_key('subcategory_id') subcategories ->foreign_key('category_id') category users: ->foreign_key('product_id') users table columns: ->city, price, product_id
Relations:
User Model: public function product(){ return $this->hasMany('App\Product'); }
Product Model: public function subcategory(){ return $this->belongsTo('App\Subcategory', 'subcategory_id'); }
Subcategory Model: public function product(){ return $this->hasMany('App\Product', 'subcategory_id'); } public function category(){ return $this->belongsTo('App\Category'); }
Category Model: public function subCategory(){ return $this->hasMany('App\Subcategory'); }
public function product(){ return $this->hasManyThrough('App\Product', 'App\Subcategory'); }
Here is my query(in ProductsController.php). $city_id, $category_id, $min_price, $max_price : demo data passed
//fetching city data $products = Product::whereHas('user', function($query) use($city_id) { $query->where('city_id', $city_id); });
//fetching category data (I am not sure about this part) $products = $products->whereHas('category', function($query) use($category_id) { $query->where('id', $category_id); });
//fetching price data $products = $products->where('price', '>=', $min_price)->where('price', '<=', $max_price);
//sub category filtering $products = $products->where('subcategory_id', 1);
$products = $products->get()->toArray();
return $products; Any help would be appreciated. Thanks in Advance.
Please or to participate in this conversation.