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

Column Sortable Laravel Package

kyslik/column-sortable

Add sortable table columns to Laravel 5.5–8. Generate clickable links in Blade, configure sortable fields and icons, and sort by related hasOne/belongsTo attributes or withCount(). Works seamlessly with pagination and query building.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Eloquent Integration: The package leverages Laravel’s Eloquent ORM, making it a natural fit for applications using Eloquent models. The Sortable trait extends Eloquent queries with sorting capabilities, aligning with Laravel’s query builder patterns.
  • Blade Integration: The @sortablelink directive integrates seamlessly with Blade templates, reducing boilerplate for UI-level sorting controls. This is particularly useful for admin panels or data tables.
  • Configurability: The package allows fine-grained control over sorting behavior (e.g., column types, relation handling, and Font Awesome icons), making it adaptable to diverse UI/UX requirements.

Integration Feasibility

  • Low Coupling: The package operates at the model and view layers without requiring deep application architecture changes. It can be adopted incrementally (e.g., per model or route).
  • Dependency Alignment: Supports Laravel 5.5–10 and PHP 8.0+, ensuring compatibility with modern Laravel stacks. The ^6.0 version constraint simplifies dependency management.
  • Relation Support: Handles complex sorting scenarios (e.g., hasOne, belongsTo) via method chaining, reducing the need for custom query logic in most cases.

Technical Risk

  • Relation Ambiguity: Misconfigured relations (e.g., unsupported relation types like hasMany) may lead to runtime errors. Requires careful testing of edge cases (e.g., self-referencing models).
  • Performance Overhead: Dynamic column checks (Schema::hasColumn) add minor DB queries per request. Mitigated by defining $sortable arrays explicitly.
  • URL Parsing Vulnerabilities: Custom sort parameters in URLs could be exploited (e.g., SQL injection via malformed input). The package’s ColumnSortableException (code 0) helps mitigate this, but application-level validation is recommended.
  • Deprecation Risk: Laravel 13+ support is recent (v8.0.0). Long-term stability depends on the package’s maintenance pace.

Key Questions

  1. Use Case Scope:
    • Is sorting required for all models, or only specific ones (e.g., admin panels)? Incremental adoption may reduce risk.
  2. Relation Complexity:
    • Does the application use advanced relations (e.g., polymorphic, many-to-many)? If so, custom overrides may be needed.
  3. UI Consistency:
    • Are Font Awesome icons or custom styling required? The package’s default classes may need adjustment.
  4. Performance Impact:
    • Will the addition of $sortable arrays or Schema::hasColumn calls materially affect query performance? Benchmark with production-like data.
  5. Error Handling:
    • How should ColumnSortableException be surfaced to users (e.g., 400 errors for invalid sorts)?
  6. Testing Coverage:
    • Are there existing tests for sorting logic? If not, prioritize testing edge cases (e.g., empty $sortable, malformed URLs).

Integration Approach

Stack Fit

  • Laravel Ecosystem: Optimized for Laravel’s Eloquent, Query Builder, and Blade. No conflicts with core Laravel features.
  • Frontend Agnostic: Works with any frontend (e.g., Livewire, Inertia, vanilla JS) as long as Blade directives are rendered.
  • API Compatibility: Can be adapted for API responses by returning sorted data in JSON (though the package is UI-focused).

Migration Path

  1. Pilot Phase:
    • Start with a single model (e.g., User) to validate integration and performance.
    • Test the @sortablelink directive in a non-critical view.
  2. Configuration:
    • Publish the config (php artisan vendor:publish --provider="Kyslik\ColumnSortable\ColumnSortableServiceProvider" --tag="config") and customize:
      • Column types (numeric/alpha/amount) and their icons.
      • Default sort direction (asc/desc).
      • Relation separators (if not using dots).
  3. Model Integration:
    • Add the Sortable trait and define $sortable arrays for target models.
    • For relations, ensure hasOne/belongsTo methods are defined.
  4. Controller Updates:
    • Replace manual orderBy calls with $model->sortable()->paginate().
    • Example:
      // Before
      $users = User::orderBy(request('sort_column', 'name'))->paginate(10);
      
      // After
      $users = User::sortable()->paginate(10);
      
  5. View Updates:
    • Replace static table headers with @sortablelink directives.
    • Example:
      @sortablelink('name', 'Username')
      @sortablelink('created_at', 'Joined')
      
  6. Error Handling:
    • Wrap sortable queries in try-catch blocks to handle ColumnSortableException gracefully.
    • Example:
      try {
          $data = Model::sortable()->paginate(10);
      } catch (ColumnSortableException $e) {
          return back()->withError('Invalid sort parameter');
      }
      

Compatibility

  • Laravel Versions: Tested on 5.5–10. For Laravel 11+, use ^6.6.0; for 12+, use ^7.0.0; for 13+, use ^8.0.0.
  • PHP Versions: Requires PHP 8.0+ (as of v7.0.0). Ensure your stack meets this requirement.
  • Database: No schema changes required. Works with any database supported by Laravel.
  • Frontend Libraries: Font Awesome 4/5 support is configurable. For other icon libraries, override the config or CSS classes.

Sequencing

  1. Dependency Installation:
    composer require kyslik/column-sortable:^6.0
    
  2. Configuration:
    • Publish and customize config/columnsortable.php.
  3. Model Updates:
    • Add Sortable trait and $sortable arrays to pilot models.
  4. Controller Updates:
    • Replace or augment existing pagination logic.
  5. View Updates:
    • Replace table headers with @sortablelink directives.
  6. Testing:
    • Validate sorting works for:
      • Direct columns (e.g., name).
      • Relations (e.g., user.name).
      • Edge cases (e.g., empty $sortable, invalid URLs).
  7. Rollout:
    • Gradually apply to additional models/routes.
    • Monitor performance and error rates.

Operational Impact

Maintenance

  • Package Updates:
    • Monitor releases for Laravel version compatibility (e.g., v8.0.0 for Laravel 13).
    • Update dependencies proactively to avoid deprecation issues.
  • Configuration Drift:
    • Centralized config (columnsortable.php) reduces maintenance overhead compared to scattered logic.
  • Custom Overrides:
    • Advanced use cases (e.g., custom joins) may require ongoing maintenance if Laravel/Eloquent APIs change.

Support

  • Debugging:
    • ColumnSortableException provides actionable error codes (0: URL parsing, 1: invalid relation, 2: unsupported relation type).
    • Logs should capture malformed sort requests for auditing.
  • User Guidance:
    • Document valid sort parameters for API consumers or frontend teams.
    • Example: "Sort by users.name or posts.title; avoid unsupported relations."
  • Dependency Support:
    • The MIT license ensures no legal barriers, but support relies on community/maintainer responsiveness.

Scaling

  • Performance:
    • Query Optimization: Explicit $sortable arrays eliminate Schema::hasColumn calls, reducing DB hits.
    • Caching: Sorting logic is query-level; consider caching paginated results if sorting is expensive (e.g., complex joins).
    • Load Testing: Validate under high concurrency, especially for tables with many sortable columns.
  • Database Load:
    • Sorting adds ORDER BY clauses, which may impact performance on large datasets. Indexes on sortable columns are critical.
    • Example: Ensure created_at is indexed if frequently sorted.
  • Horizontal Scaling:
    • Stateless nature of the package ensures compatibility with Laravel Horizon or queue workers for background sorting tasks.

Failure Modes

Failure Scenario Impact Mitigation
Malformed sort URL parameter ColumnSortableException (code 0) Validate input; return 400 errors for invalid sorts.
Invalid relation in sort parameter ColumnSortableException (code 1) Log and ignore; default to a safe sort column (e.g., id).
Unsupported relation type ColumnSortableException (code 2) Document supported relations; override for custom logic.
Missing indexes on sortable columns Slow queries Add indexes; monitor query performance with Laravel Debugbar or Query Logger.
Package version incompatibility Broken functionality Pin to a stable version
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4