title: Laravel: How to merge 2 different database queries into one and access the results?
body: <p>I'm trying to retrieve the total and the number of user likes in a post from the database.</p>
  <p>Right now, I'm sending 2 different queries and retrieving the results.</p>
  <p>But I would like to merge both queries into one and get the results from one database request only.</p>
  <p>This is what I tried:</p>
  <pre class="lang-php prettyprint-override"><code>$userId = auth('sanctum')-&gt;user()-&gt;id;
  
  $userLikesCountQuery = DB::table(&quot;likes&quot;)
      -&gt;select('SUM(like) as user_count')
      -&gt;where('user_id', $userId);
  
  $data = DB::table(&quot;likes&quot;)
      -&gt;select(
          DB::raw('SUM(like) as count'),
          $userLikesCountQuery,
      )
      -&gt;first();
  
  return [
     'meta' =&gt; [
          'count' =&gt; $data-&gt;count ?? 0,
          'user_count' =&gt; $data-&gt;user_count ?? 0,
     ],
  ];
  </code></pre>
  <p>This is resulting in the following error: <code>stripos(): Argument #1 ($haystack) must be of type string, Illuminate\Database\Query\Builder given</code></p>
  <p>Laravel does something similar when eager loading relationships with Eloquent.</p>
  <p>How can I achieve this?</p>