title: Laravel 5: sort products by categories,
body: <p>I dont have a lot of experience with laravel but i am trying to sort my products on categories... 
  I can already sort all products but not by categorie. </p>
  
  <p>Could you guys help me out?</p>
  
  <p>Model:</p>
  
  <pre><code>class Product extends Model {
  
  
  protected $table = 'products';
  
  
  public function getCategoriesListAttribute(){
      return $this-&gt;categories()-&gt;lists('id');
  }
  
  
  public function categories(){
      return $this-&gt;belongsToMany('App\Modules\Webshop\Models\ProductCategory', 'category_product', 'product_id', 'category_id')-&gt;withTimestamps();
  }}
  </code></pre>
  
  <p>Products table:</p>
  
  <pre><code>    Schema::create('products', function(Blueprint $table)
      Schema::create('category_product', function(Blueprint $table)
      Schema::create('product_categories', function(Blueprint $table)
      Schema::create('product_tag', function(Blueprint $table)
  </code></pre>
  
  <p>Controller:</p>
  
  <pre><code>class ProductsController extends Controller {
  
      public function __construct()
      {
          //$this-&gt;middleware('auth');
      }
  
      public function index()
      {
          $viewmodel = array(
              "categories"=&gt; ProductCategory::where('visible', '1')-&gt;get(),
              "products" =&gt; Product::has('categories')-&gt;get(),
              "page"=&gt;Page::where('href','=', '/')-&gt;first(),
          );
          return view('Webshop::frontend.view.products.index', $viewmodel);
      }
  
  }
  </code></pre>
  
  <p>The index() shows only the products who have any category.</p>
  
  <p>If you guys need more information feel free to ask :)</p>
  
  <p>EDIT:</p>
  
  <p>I am trying this in my controller.</p>
  
  <pre><code> public function index()
  {
      $viewmodel = array(
          "products" =&gt; Product::with('categories')-&gt;where('category_id','23'),
      );
      return view('Webshop::frontend.view.products.index', $viewmodel);
  }
  </code></pre>
  
  <p>and this:</p>
  
  <pre><code>  $viewmodel = array(
          "products" =&gt; Product::leftJoin('category_product', 'category_product.product_id', '=', 'products.id')
                          -&gt;leftJoin('product_categories', 'product_categories.id', '=', 'category_product.category_id')
                          -&gt;where('category_id', 23)
                          -&gt;first(['products.*']),
      );
      return view('Webshop::frontend.view.products.index', $viewmodel);
  </code></pre>
  
  <p>I have a category with id 23.</p>