title: Laravel 5: How to group a collection dynamically by one column or another depending on item's column value?
body: <p>I have a collection of items as a result of an Eloquent model query. What I need to do is to somehow group the items of that collection either by one column or another depending on a specific item's field value if it satisfies a condition. Is it possible to use a function inside the <code>groupBy()</code> or there is another way to do this, if possible at all? I'll provide additional details if needed in case there is a theoretical solution for such situation.</p>
  
  <p>Update:</p>
  
  <p>Here is the code where I create two separate collections and then group each of them:</p>
  
  <pre><code>...
  
  // First collection which is grouped by grouping_field1
  $non_grouped_products = Product::with("some_relation")
      -&gt;whereHas("some_relation", function($q) {
          $q-&gt;where("conditional_field", 0)
              -&gt;where("some_field1", 1)
              -&gt;orWhere("some_field2", 0);
      })-&gt;where("some_field3", "some_value")
      -&gt;where("some_field4", "some_value2")
      -&gt;get()
      -&gt;groupBy("grouping_field1");
  
  // Second collection which is grouped by grouping_field2
  $products = Product::with("some_relation")
      -&gt;whereHas("some_relation", function($q) {
          $q-&gt;where("conditional_field", 1)
              -&gt;where("some_field1", 1)
              -&gt;orWhere("some_field2", 0);
      })-&gt;where("some_field3", "some_value")
      -&gt;where("some_field4", "some_value2")
      -&gt;get()
      -&gt;groupBy("grouping_field2");
  
  $all_products = [];
  
  // Here is where I join the collections
  foreach ($products as $key =&gt; $product) {
      $all_products[$key] = $product;
  }
  foreach ($non_grouped_products as $key =&gt; $product) {
      $all_products[$key] = $product;
  }
  
  $merged_collection = new Collection($all_products);
  
  ...
  </code></pre>
  
  <p>Why I need to avoid making two collections is because I want to make an <code>orderBy()</code> just once instead of doing it separately on each of initial collections as after merging the ordering is not correct anymore.
  I need to check the value of the <code>conditional_field</code> and if it satisfies one or another condition, I need to group the item by one of the grouping fields.</p>
  
  <p>I hope I was explicit enough. If you need some other details, I'll provide them to you so it will be easier for you to understand all the circumstances and what specifically I need to achieve. Thank you in advance! :)</p>