PHP code example of oyedele / laravel-custom-pagination

1. Go to this page and download the library: Download oyedele/laravel-custom-pagination library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

oyedele / laravel-custom-pagination example snippets




namespace Oyedele\CustomPagination\Traits;

trait CustomPagination
{
    public function paginate(
        object $request,
        $model,
        $otherParams = null
    ): array {
        $records_per_page = $request->query('per_page') ?? 20;
        $page = intval($request->query('page'));

        $totalRecords = $model->count();

        $pagination = [
            'total' => null,
            'current' => null,
            'from' => null,
            'to' => null,
            'pages' => null,
        ];

        $page = ($page > 1) ? $page : 1;

        $offset = ($page > 1)
            ? ($records_per_page * ($page - 1))
            : 0;

        $pages = ceil($totalRecords / $records_per_page);

        $modelRecords = $model
            ->offset($offset)
            ->limit($records_per_page)
            ->get();

        if ($modelRecords->count()) {
            $pagination['total'] = $totalRecords;
            $pagination['current'] = $page;
            $pagination['from'] = $offset + 1;
            $pagination['to'] = min(
                $offset + $records_per_page,
                $totalRecords
            );
            $pagination['pages'] = $pages;
        }

        return [
            'data' => $modelRecords,
            'pagination' => $pagination
        ];
    }
}

use Oyedele\CustomPagination\Traits\CustomPagination;

class UserController extends Controller
{
    use CustomPagination;
}

public function index(Request $request)
{
    $users = User::query();

    $result = $this->paginate(
        $request,
        $users
    );

    return response()->json([
        'status' => true,
        'message' => 'Users retrieved successfully',
        'data' => $result['data'],
        'pagination' => $result['pagination']
    ]);
}



namespace Oyedele\CustomPagination;

use Illuminate\Support\ServiceProvider;

class CustomPaginationServiceProvider extends ServiceProvider
{
    public function register(): void
    {
    }

    public function boot(): void
    {
    }
}
text
laravel-custom-pagination/
├── src/
│   ├── Traits/
│   │   └── CustomPagination.php
│   └── CustomPaginationServiceProvider.php
├── tests/
├── composer.json
├── README.md
└── LICENSE