Laravel Eloquent Pagination, How To Count Before Pagination With Filters?

Here my code :

$prestations = Prestation::with('service','facility','')
            ->whereHas('service', function ($query) use ($searchService) {
                $query->select('id','name')->where('name', 'regexp', "/$searchService/i");
            ->whereHas('facility', function ($query) use ($searchPartenaire) {
                $query->select('id','name')->where('name', 'regexp', "/$searchPartenaire/i");
            ->whereHas('', function ($query) use ($searchFiliale) {
                $query->select('id','name')->where('name', 'regexp', "/$searchFiliale/i");
                ->where('name', 'regexp', "/$search/i")
                ->orderBy($orderBy, $orderDirection)

        $res = [
            'results' => $prestations,
            'total' => Prestation::all()->count(),

        return $res;

Hi, actually i get all "Prestation" items at 'total', but i need the real total just before the simplePaginate(50); after all of my conditions. How i can give this value at 'total' without disturbing my code ? Thank you !



Eloquent queries are very flexible and you can store them as variables before executing them.

Here is a simplified example of what you could do:

// Start your query and store it as a variable
$query = Prestation::where('name', 'regexp', "/$search/i");

// Now count the total number of entries which will return
$count = $query->count();

// Finally, do your pagination
$prestations = $query->simplePaginate(50);

Of course you can add all of your other constraints to the query, i've just removed them to simplify the answer.