jfurnas's avatar

total() not working with get()

Hello there,

I am creating a search page that dynamically builds the where() clause based on input provided by a form that has been submitted.

In doing so, I have had to use the ->get() method to get the results, and have lost the ability to use total() on my paginate ability. How can I restore this?

The code I am working with is;

    if (!empty($request->parameters) || !empty($request->keywords)) {
        $query = Grievance::query();
        if (!empty($request->parameters)) {
            // The parameters value is not empty, so they are searching for a grievant name
            $query = $query->Where('name','LIKE','%'. $request->parameters .'%');
        }
        if (!empty($request->keywords)) {
            $array = explode(',',$request->keywords);
            foreach ($array as $item) {
                $query = $query->orWhere('description','LIKE','%'. $item .'%');
            }
        }
        $query->sortable();
        $query->paginate(config('grievances.sort_number', 10));
        $results = $query->get();
    }

When I run $results->total() I get an unknown Method 'total'. The pagination is working, as it's limiting the results that are displayed on the page, but a dd($results) does not show the ->total() ->first() ->last() etc, only the limit and offset values.

0 likes
2 replies
lostdreamer_nl's avatar
Level 53

You're not returning the pagination, and if you did, you couldnt call get() on it.

        $query->paginate(config('grievances.sort_number', 10));
    // $query is still a query, not a paginated query
        $results = $query->get();
        $results = $query->paginate(config('grievances.sort_number', 10));
    // $results now is a paginated query
    // $results->total(); will now work as well
1 like
jfurnas's avatar

Hmm, you are right. Not sure how I missed that. Storing the return value of the query would have been nice to begin with :)

Thanks! Something so simple was racking my brain all day yesterday and this morning.

Please or to participate in this conversation.