title: Laravel saving ordered list of eloquent models
body: <p>I'm creating a food menu which the administrator can order/sort by dragging and dropping. This menu consists of multiple categories (ProductCategory) and products (Product).</p>
  <p>I'm using <a href="https://github.com/voidberg/html5sortable" rel="noreferrer">HTML5Sortable</a> on the client-side to allow nested d&amp;d. The markup is pretty simple:</p>
  <pre><code>&lt;div class=&quot;categories&quot;&gt;
      @foreach($categories as $category)
      &lt;div class=&quot;category&quot;&gt;
          @foreach($category-&gt;products as $product)
          &lt;div class=&quot;products&quot;&gt;
              &lt;div class=&quot;&quot;product&quot; data=id=&quot;{{ $product-&gt;id }}&quot;&gt;
                   {{ $product-&gt;name }}
              &lt;/div&gt;
          &lt;/div&gt;&lt;!-- /products !--&gt;
          @endforeach
      &lt;/div&gt;&lt;!-- /category !--&gt;
      @endforeach
  &lt;/div&gt;
  </code></pre>
  <p>And the corresponding javascript:</p>
  <pre><code>$('.categories').sortable({
      items: '.category'
  });
  $('.products').sortable({
      items: '.product'
  });
  
  // Will be called when the user is done repositioning the products and categories
  function getOrderedList() {
      var data = {};
  
      $('.categories').find('.category').map(function(i) {
          var category = $(this);
          data[i] = {};
          data[i].id = category.data('id');
          data[i].products = category.find('.product').map(function() {
              return $(this).data('id');
          }).get();
      });
  
      data = JSON.stringify(data); // Send data to server
  }
  </code></pre>
  <p>The function <code>getOrderedList</code> will send a JSON string back to Laravel, which contains the sorted category id's and product id's:</p>
  <pre><code>{&quot;0&quot;:{&quot;id&quot;:1,&quot;products&quot;:[2,3,1,4,5,6,7,8,9,10]},&quot;1&quot;:{&quot;id&quot;:2,&quot;products&quot;:[11,12,13,14]},&quot;2&quot;:{&quot;id&quot;:3,&quot;products&quot;:[15,16,17,18]}}
  </code></pre>
  <p>How would I make this work on the back-end? I guess I must store this array somewhere in the database and later find and order the models by the id's?</p>
  <p>In short: What is a clean and flexible solution for sorting (nested) models (within Laravel)?</p>