jlrdw's avatar
Level 75

Manual pagination episode 3 (It is a guide not question)

A question came up how to paginate using the DB Facade. And since at times it's used instead of query builder or eloquent, here goes:

  • You have to have a count of results.

And just a simple example:

    public function indexdb()
    {
        $page = !empty(Request::input('page')) ? Request::input('page') : '1';
        $search = !empty(Request::input('search')) ? Request::input('search') : '';
        $sch = $search . "%";
        $perpage = "5";
        $offset = ($page - 1) * $perpage;
        $krows = DB::select('SELECT COUNT(dogid) as total FROM dc_dogs WHERE dogname LIKE :search', [':search' => $sch]);
        $numrows = $krows[0]->total;
        $pagingQuery = "LIMIT {$offset}, {$perpage}";
        $quy = DB::select("SELECT * FROM dc_dogs WHERE dogname LIKE :search " . $pagingQuery, [':search' => $sch]);
        $dogs = new LengthAwarePaginator($quy, $numrows, $perpage);
        $qs = ['search' => $search, 'page' => $page];
        $title = 'Dogs';
        return view('dog.indexg', compact('dogs', 'title', 'qs'));
        }

And in the view:

@php echo str_replace('/?', '?', $dogs->appends($qs)->render('custompager')) @endphp

// or if no custom pager

@php echo str_replace('/?', '?', $dogs->appends($qs)->render()) @endphp

Here is an example of a more complex query using the DB Facade.

https://laracasts.com/discuss/channels/laravel/sql-native-to-query-builder

Of course have the proper use statements at top.

use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\LengthAwarePaginator;

Use proper bindings.

0 likes
1 reply

Please or to participate in this conversation.