Pagination in laravel 5

Laravel provides pagination for Eloquent results which comes out of the box features but for custom data set we need to create paging.i'm using laravel5 LengthAwarePaginator class to show you how to create a pagination from a array of data.

Laravel Pagination

Step 1: Controller – app/Http/Controller/RecordsController.php


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Http\Requests;

class RecordsController extends Controller

    public function items(Request $request)
        $items = [

        // Get current page form url e.x. &page=1
        $currentPage = LengthAwarePaginator::resolveCurrentPage();

        // Create a new Laravel collection from the array data
        $itemCollection = collect($items);

        // Define how many items we want to be visible in each page
        $perPage = 1;

        // Slice the collection to get the items to display in current page
        $currentPageItems = $itemCollection->slice(($currentPage * $perPage) - $perPage, $perPage)->all();

        // Create our paginator and pass it to the view
        $paginatedItems = new LengthAwarePaginator($currentPageItems, count($itemCollection), $perPage);

        // set url path for generted links

        return view('records_view', ['records' => $paginatedItems]);

Step 2: View (resources/views/records_view.blade.php) file should look like this.

<h1>Records List</h1>
@foreach ($records as $record) 
   <li> {{ $record }} </li>
{{ $records->links() }}

Step 3: Now comes to the routing app/Http/Routes.php.


Please feel free to comment below for suggestions and problems.

No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...