Search code examples
paginationlaravel-5take

use pagination for limited records in laravel 5.2


I am trying to use paginate method for 12 records. I need 12 results where first 6 results comes in first page and the rest 6 results in second page. I used the below code in the controller,

$collection = User::take(12)->whereHas('roles', function($q) {
            $q->where('slug', 'member');

        }
        )->where('status','1')->OrderBy('last_login','desc');

I used take() to get 12 records and used paginate(6) to display 6 results in one page as this,

$collection = $collection->paginate(6);
return View('preferred_matches')->with(array('collection'=>$collection));

In my view , I gave links like this,

{{ $collection->links() }}

But the take(12) is not working. 6 results appears in each page ,but more than 12 results are displaying. How can I use limited records for pagination. Thanks in advance.


Solution

  • Laravel does not support limit on its default pagination, but if limit can be placed on pagination with the following steps:

    First create a static method inside a model (Suppose User Model)

    First step: Add this two line after namespace of User model

    use Illuminate\Pagination\LengthAwarePaginator;
    use Illuminate\Support\Collection;
    

    Second step: inside User model just type the below method

    public static function customPaginate($items,$perPage)
    {
        //Get current page form url e.g. &page=6
        $currentPage = LengthAwarePaginator::resolveCurrentPage();
    
        //Create a new Laravel collection from the array data
        $collection = new Collection($items);
    
        //Define how many items we want to be visible in each page
        $perPage = $perPage;
    
        //Slice the collection to get the items to display in current page
        $currentPageSearchResults = $collection->slice($currentPage * $perPage, $perPage)->all();
    
        //Create our paginator and pass it to the view
        $paginatedSearchResults = new LengthAwarePaginator($currentPageSearchResults, count($collection), $perPage);
    
       return $paginatedSearchResults;
    }
    

    Third step: In route or controller type the code to see the result (suppose in routes.php)

    Route::get('/', function(){
       $users = DB::table('users')->limit(20)->get();
       $paginated_result = App\User::customPaginate($users,3);
       //dd($paginated_result);
       return view('show')->with('paginated_result',$paginated_result);
    });
    

    Hopefully, It will work.