title: Want to fetch data from three tables in laravel 5.2
body: <p>I have a little query in which I need your help, Please have a look below.</p>
  
  <p>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.</p>
  
  <p>Below is my tables and Eloquent relations. I am using Laravel 5.2.</p>
  
  <pre><code>products -&gt;foreign_key('subcategory_id')
  subcategories -&gt;foreign_key('category_id')
  category
  users: -&gt;foreign_key('product_id')
  users table columns: -&gt;city, price, product_id 
  </code></pre>
  
  <p>Relations:</p>
  
  <pre><code>User Model:
  public function product(){
      return $this-&gt;hasMany('App\Product');
  }
  
  Product Model:
  public function subcategory(){
      return $this-&gt;belongsTo('App\Subcategory', 'subcategory_id');
  }
  
  
  Subcategory Model:
  public function product(){
      return $this-&gt;hasMany('App\Product', 'subcategory_id');
  }
  public function category(){
      return $this-&gt;belongsTo('App\Category');
  }
  
  
  Category Model:
  public function subCategory(){
      return $this-&gt;hasMany('App\Subcategory');
  }
  
  public function product(){
     return $this-&gt;hasManyThrough('App\Product', 'App\Subcategory');
  }
  </code></pre>
  
  <p>Here is my query(in ProductsController.php).</p>
  
  <pre><code>$city_id, $category_id, $min_price, $max_price : demo data passed
  
  //fetching city data
  $products = Product::whereHas('user', function($query) use($city_id) {
       $query-&gt;where('city_id', $city_id);
  });
  
  //fetching category data (I am not sure about this part)
  $products =  $products-&gt;whereHas('category', function($query) use($category_id) {
      $query-&gt;where('id', $category_id);
  });
  
  //fetching price data
  $products = $products-&gt;where('price', '&gt;=', $min_price)-&gt;where('price', '&lt;=', $max_price);
  
  //sub category filtering
  $products = $products-&gt;where('subcategory_id', 1);
  
  
  $products = $products-&gt;get()-&gt;toArray();
  
  return $products;
  </code></pre>
  
  <p>Any help would be appreciated. Thanks in Advance.</p>