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

Tablesort Laravel Package

contao-components/tablesort

contao-components/tablesort adds client-side table sorting to Contao projects. Easily enable sortable columns for HTML tables, improving data presentation and usability in the backend or frontend with minimal setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require contao-components/tablesort
    npm install tablesort --save
    

    Ensure tablesort.js and tablesort.css are published to your public/js and public/css directories (check the package docs for exact paths).

  2. Basic Usage in Blade

    <table id="sortable-table" class="tablesort">
        <thead>
            <tr>
                <th data-sort="string">Name</th>
                <th data-sort="number">Age</th>
                <th data-sort="date">Join Date</th>
            </tr>
        </thead>
        <tbody>
            <!-- Table rows -->
        </tbody>
    </table>
    
    <script>
        $(document).ready(function() {
            $('#sortable-table').tablesort();
        });
    </script>
    
  3. First Use Case

    • Sort a Laravel-generated table (e.g., from a foreach loop in Blade) by clicking column headers.
    • Example: Sort a user list by created_at (date) or name (string).

Implementation Patterns

Workflow Integration

  1. Dynamic Table Generation Use Laravel Blade to generate tables dynamically (e.g., from Eloquent queries):

    @foreach($users as $user)
        <tr>
            <td>{{ $user->name }}</td>
            <td>{{ $user->age }}</td>
            <td>{{ $user->created_at->format('Y-m-d') }}</td>
        </tr>
    @endforeach
    

    Wrap in <table class="tablesort"> and initialize with tablesort().

  2. Server-Side Sorting (Recommended for Large Datasets)

    • Use AJAX to fetch sorted data from Laravel routes:
      $('#sortable-table').tablesort({
          onSort: function(table, column) {
              $.get('/users/sort', { column: column, order: 'asc' }, function(data) {
                  $('#sortable-table tbody').html(data.html);
              });
          }
      });
      
    • Laravel route:
      Route::get('/users/sort', [UserController::class, 'sort']);
      
    • Controller:
      public function sort(Request $request) {
          $users = User::orderBy($request->column, $request->order)->get();
          return response()->json([
              'html' => view('users.table_rows', compact('users'))->render()
          ]);
      }
      
  3. Custom Sorting Logic Extend tablesort with custom comparators:

    $('#sortable-table').tablesort({
        sortFunction: function(a, b, column) {
            if (column === 'status') {
                const statusOrder = { 'active': 1, 'inactive': 2 };
                return statusOrder[a] - statusOrder[b];
            }
        }
    });
    
  4. Integration with Laravel Collectives Pair with HTML::table() for cleaner Blade syntax:

    {{ HTML::table('sortable', $users->toArray(), ['name', 'age', 'created_at']) }}
    

Gotchas and Tips

Pitfalls

  1. CSS Conflicts

    • tablesort.css may override Bootstrap/FlatUI table styles. Override with:
      .tablesort th.sort-asc::after {
          content: " ↑";
          color: #007bff !important;
      }
      
  2. Case-Sensitive Sorting

    • Default string sorting is case-sensitive. Use localeCompare for case-insensitive:
      sortFunction: (a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' })
      
  3. Nested Tables

    • Avoid nesting tables inside sortable tables; tablesort may misbehave.
  4. Initial Load State

    • If the table loads pre-sorted, reset the UI:
      $('#sortable-table').trigger('update');
      

Debugging Tips

  • Check Console for Errors Ensure tablesort.js is loaded and no 404s appear for dependencies (e.g., jQuery).
  • Verify data-sort Attributes Missing or incorrect attributes (e.g., data-sort="invalid") will break sorting.
  • Inspect AJAX Payloads For server-side sorting, log the column/order params in Laravel to confirm they match the request.

Extension Points

  1. Custom Icons Replace default arrows with Font Awesome:

    $('#sortable-table').tablesort({
        ascendingIcon: '<i class="fas fa-sort-up"></i>',
        descendingIcon: '<i class="fas fa-sort-down"></i>'
    });
    
  2. Multi-Column Sorting Use a plugin like tablesort-multicol or implement a custom solution with shift+click handlers.

  3. Laravel Service Provider Register a global JS asset for tablesort:

    // app/Providers/AppServiceProvider.php
    public function boot() {
        View::composer('*', function ($view) {
            $view->with('tablesortScript', '<script src="/js/tablesort.js"></script>');
        });
    }
    

    Then include $tablesortScript in your layout.

  4. Localization Override text labels (e.g., for RTL languages):

    $('#sortable-table').tablesort({
        text: {
            asc: '↑',
            desc: '↓'
        }
    });
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky