Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Paginator Laravel Package

anh/paginator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation:

    composer require anh/paginator:0.2.*
    
  2. Basic Usage: For Eloquent queries or QueryBuilder:

    use Anh\Paginator\Paginator;
    
    $paginator = new Paginator();
    $users = $paginator->paginate(User::query(), 1, 10); // Page 1, 10 items per page
    

    For arrays:

    $data = [/* array data */];
    $paginatedData = $paginator->paginate($data, 1, 10);
    
  3. First Use Case: Render paginated results in a Blade view:

    return view('users.index', ['users' => $users]);
    

    Then in Blade:

    @foreach($users as $user)
        {{ $user->name }}
    @endforeach
    

Implementation Patterns

Core Workflows

  1. Query-Based Pagination:

    // Eloquent
    $posts = $paginator->paginate(Post::query()->where('published', true), $page, 15);
    
    // QueryBuilder
    $posts = $paginator->paginate(DB::table('posts')->where('status', 'active'), $page, 15);
    
  2. Array-Based Pagination:

    $items = $paginator->paginate($arrayData, $page, 20, ['preserveKeys' => true]);
    
  3. Custom Adapter Integration:

    $adapterResolver = new AdapterResolver();
    $adapterResolver->addAdapter(\App\CustomAdapter::class);
    $paginator = new Paginator($adapterResolver);
    
  4. View Rendering:

    $view = new AdaptiveView();
    $view->setTemplates([
        'default' => resource_path('views/pagination/default.blade.php'),
    ]);
    echo $view->render($posts, route('posts.index', ['page' => '%page%']));
    

Integration Tips

  • Laravel Service Provider: Bind the paginator to the container for dependency injection:

    $this->app->singleton(Paginator::class, function ($app) {
        return new Paginator(new AdapterResolver());
    });
    
  • Middleware for Page Validation: Validate $page parameter in route middleware:

    public function handle($request, Closure $next)
    {
        $page = (int) $request->query('page', 1);
        if ($page < 1) abort(400, 'Invalid page number');
        return $next($request);
    }
    
  • Dynamic Per-Page Limits: Use request input for flexible limits:

    $perPage = (int) $request->input('per_page', config('pagination.per_page', 15));
    $items = $paginator->paginate($data, $page, $perPage);
    

Gotchas and Tips

Pitfalls

  1. Adapter Auto-Detection:

    • The library auto-detects adapters (e.g., ArrayAdapter for arrays, DoctrineOrmAdapter for Doctrine queries).
    • Gotcha: If you pass a raw array but forget to include Anh\Paginator\Adapter\ArrayAdapter in composer.json, the paginator will fail silently or throw an error.
    • Fix: Explicitly add the adapter or ensure the library is installed correctly.
  2. Page Number Handling:

    • The library assumes page starts at 1 (not 0). Passing 0 or negative values may cause unexpected behavior.
    • Tip: Always validate and sanitize the page parameter:
      $page = max(1, (int) $request->query('page'));
      
  3. Doctrine ORM Adapter:

    • Requires Doctrine ORM (doctrine/orm). If not installed, the adapter will fail.
    • Tip: Check for Doctrine dependencies in composer.json:
      "require": {
          "doctrine/orm": "^2.0"
      }
      
  4. Array Key Preservation:

    • The ArrayAdapter does not preserve keys by default. Use the preserveKeys option:
      $paginator->paginate($array, $page, $limit, ['preserveKeys' => true]);
      

Debugging

  1. Adapter Resolution Issues:

    • If pagination fails silently, check the AdapterResolver:
      $adapterResolver = $paginator->getAdapterResolver();
      $adapter = $adapterResolver->resolveAdapter($data);
      if (!$adapter) {
          throw new \RuntimeException('No adapter found for data type: ' . gettype($data));
      }
      
  2. View Rendering Errors:

    • Ensure template paths are correct and files exist. Use absolute paths for debugging:
      $view->setTemplates([
          'default' => __DIR__ . '/../resources/views/pagination/default.blade.php',
      ]);
      

Extension Points

  1. Custom Adapters:

    • Implement Anh\Paginator\Adapter\AdapterInterface:
      class MyCustomAdapter implements AdapterInterface
      {
          public function paginate($data, $page, $limit, array $options = [])
          {
              // Custom logic here
              return new Page($data, $page, $limit, $totalItems);
          }
      }
      
    • Register the adapter with AdapterResolver:
      $adapterResolver->addAdapter(MyCustomAdapter::class);
      
  2. Custom Views:

    • Extend Anh\Paginator\View\AdaptiveView to add custom templates or logic:
      class CustomView extends AdaptiveView
      {
          protected function getDefaultTemplate()
          {
              return 'custom::pagination.default';
          }
      }
      
  3. Page Class Extensions:

    • Extend Anh\Paginator\Page to add custom methods or properties:
      class CustomPage extends Page
      {
          public function getUrl($page)
          {
              return route('custom.route', ['page' => $page]);
          }
      }
      
    • Pass your custom class to the paginator:
      $paginator->setPageClass(CustomPage::class);
      

Configuration Quirks

  1. Default Values:

    • The library does not provide default configuration (e.g., per_page). Set these in your application:
      config(['pagination.per_page' => 15]);
      
  2. URL Generation:

    • The AdaptiveView uses %page% as a placeholder. Customize this in your templates or override the generateUrl method.
  3. CSS Integration:

    • The included pagination.css is Foundation-based. Override or extend it to match your project’s styles:
      /* Custom styles */
      .pagination {
          @apply text-center;
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime