44
55use Illuminate \Database \Eloquent \Builder ;
66use Illuminate \Database \Eloquent \Collection as EloquentCollection ;
7+ use Illuminate \Database \Query \Builder as QueryBuilder ;
78use Illuminate \Pagination \Paginator ;
89use Illuminate \Support \Collection ;
910use Illuminate \Support \Facades \DB ;
@@ -287,12 +288,12 @@ private function buildQueries(): Collection
287288 }
288289
289290 /**
290- * Compiles all queries to one big one which binds everything together
291- * using UNION statements.
292- *
293- * @return \Illuminate\Support\Collection|\Illuminate\Contracts\Pagination\LengthAwarePaginator
294- */
295- private function getIdAndOrderAttributes ()
291+ * Compiles all queries to one big one which binds everything together
292+ * using UNION statements.
293+ *
294+ * @return
295+ */
296+ private function getCompiledQueryBuilder (): QueryBuilder
296297 {
297298 $ queries = $ this ->buildQueries ();
298299
@@ -303,12 +304,22 @@ private function getIdAndOrderAttributes()
303304 $ queries ->each (fn (Builder $ query ) => $ firstQuery ->union ($ query ));
304305
305306 // sort by the given columns and direction
306- $ firstQuery ->orderBy (DB ::raw ($ this ->makeOrderBy ()), $ this ->orderByDirection );
307+ return $ firstQuery ->orderBy (DB ::raw ($ this ->makeOrderBy ()), $ this ->orderByDirection );
308+ }
309+
310+ /**
311+ * Paginates the compiled query or fetches all results.
312+ *
313+ * @return \Illuminate\Support\Collection|\Illuminate\Contracts\Pagination\LengthAwarePaginator
314+ */
315+ private function getIdAndOrderAttributes ()
316+ {
317+ $ query = $ this ->getCompiledQueryBuilder ();
307318
308319 // get all results or limit the results by pagination
309320 return $ this ->perPage
310- ? $ firstQuery ->paginate ($ this ->perPage , ['* ' ], $ this ->pageName , $ this ->page )
311- : $ firstQuery ->get ();
321+ ? $ query ->paginate ($ this ->perPage , ['* ' ], $ this ->pageName , $ this ->page )
322+ : $ query ->get ();
312323
313324 // the collection will be something like:
314325 //
@@ -358,6 +369,19 @@ private function getModelsPerType($results)
358369 // ]
359370 }
360371
372+ /**
373+ * Retrieve the "count" result of the query.
374+ *
375+ * @param string $terms
376+ * @return integer
377+ */
378+ public function count (string $ terms = null ): int
379+ {
380+ $ this ->initializeTerms ($ terms ?: '' );
381+
382+ return $ this ->getCompiledQueryBuilder ()->count ();
383+ }
384+
361385 /**
362386 * Initialize the search terms, execute the search query and retrieve all
363387 * models per type. Map the results to a Eloquent collection and set
0 commit comments