- How do I add sortable columns to a Laravel Eloquent model?
- Use the `Sortable` trait in your Eloquent model and define a `$sortable` array with column names. For example, `protected $sortable = ['name', 'created_at'];`. The package will automatically handle sorting logic for these columns.
- Can I sort by relationships like `hasOne` or `belongsTo` in this package?
- Yes, the package supports sorting by relationships. Define the relationship in your model (e.g., `public function user() { return $this->belongsTo(User::class); }`) and include it in the `$sortable` array with dot notation, like `'user.name'`.
- What Laravel versions does `kyslik/column-sortable` support?
- The package officially supports Laravel 5.5 through 10.x. However, newer versions like Laravel 10 may require validation for full compatibility, as the package’s maturity varies across versions.
- How do I generate sortable links in Blade views?
- Use the `@sortablelink` Blade directive in your table headers. For example, `@sortablelink('name', 'Name')` will generate a link that toggles sorting for the `name` column. You can also customize icons using the `icon` parameter.
- Does this package work with pagination and filtering?
- Yes, it integrates seamlessly with Laravel’s pagination. Replace `paginate()` with `sortable()->paginate()` in your controller, and the package will handle sorting while maintaining pagination functionality.
- How do I set default sorting for a model?
- Pass an array to the `sortable()` method in your controller with the default column and direction, like `sortable(['name' => 'desc'])->paginate()`. Alternatively, configure defaults in the published config file.
- Is there a way to customize the sort icons or classes?
- Yes, the package supports customization via a published config file. You can define default icon classes (e.g., Font Awesome) and modify separators for relation sorting to match your UI design.
- What if I need to sort by a column not defined in `$sortable`?
- The package checks the database schema dynamically using `Schema::hasColumn()` if a column isn’t in `$sortable`. However, this adds overhead, so it’s recommended to predefine all sortable columns for performance.
- How do I handle security concerns like SQL injection with user-provided sort parameters?
- Always validate and sanitize the `sort` and `direction` query parameters in your controller or middleware. Use a whitelist (e.g., `$allowedSortableColumns`) to restrict sorting to predefined columns and prevent malicious input.
- Are there alternatives to `kyslik/column-sortable` for Laravel column sorting?
- Yes, alternatives include `spatie/laravel-query-builder` for more advanced query customization or `laravel-excel` for sorting in exported data. However, `kyslik/column-sortable` is lightweight and focused specifically on Eloquent sorting with Blade integration.