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

Default Model Sorting Laravel Package

stephenjude/default-model-sorting

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require stephenjude/default-model-sorting
    
  2. Apply Trait: Add use Stephenjude\DefaultModelSorting\Traits\DefaultOrderBy; to your Eloquent model.
    class Article extends Model
    {
        use DefaultOrderBy;
    
        protected static $orderByColumn = 'title';
    }
    
  3. First Use Case: Immediately apply default sorting to queries:
    $articles = Article::all(); // Automatically ordered by `title` ASC
    

Where to Look First

  • Trait Documentation: Focus on DefaultOrderBy trait in stephenjude/default-model-sorting/src/Traits/DefaultOrderBy.php.
  • Model Configuration: Check $orderByColumn and $orderByColumnDirection in your model.
  • Published Config: Run php artisan vendor:publish --provider="Stephenjude\DefaultModelSorting\ServiceProvider" to inspect default settings.

Implementation Patterns

Core Workflow

  1. Define Default Sorting:
    class Post extends Model
    {
        use DefaultOrderBy;
    
        protected static $orderByColumn = 'published_at';
        protected static $orderByColumnDirection = 'desc';
    }
    
  2. Override in Queries: Temporarily override default sorting:
    Post::orderBy('views', 'desc')->get(); // Ignores default
    
  3. Dynamic Column Selection: Use a closure for dynamic defaults:
    protected static $orderByColumn = function() {
        return request()->wantsJson() ? 'id' : 'title';
    };
    

Integration Tips

  • APIs: Combine with API resources for consistent client-side sorting.
  • Admin Panels: Useful for backend listings (e.g., Laravel Nova, Filament).
  • Scopes: Extend with custom scopes:
    public function scopeActive($query)
    {
        return $query->where('is_active', true)->orderByDefault();
    }
    
  • Testing: Mock the trait for unit tests:
    $model = new class extends Model {
        use DefaultOrderBy;
        protected static $orderByColumn = 'test_column';
    };
    

Advanced Patterns

  • Global Defaults: Publish config to set app-wide defaults:
    // config/default-model-sorting.php
    'default_column' => 'created_at',
    'default_direction' => 'asc',
    
  • Polymorphic Models: Useful for sorting relationships:
    class Comment extends Model
    {
        use DefaultOrderBy;
    
        protected static $orderByColumn = 'created_at';
    }
    
  • Soft Deletes: Works seamlessly with SoftDeletes trait.

Gotchas and Tips

Common Pitfalls

  1. Query Overrides:
    • Issue: Default sorting is ignored when manually chaining orderBy().
    • Fix: Use orderByDefault() to reapply defaults:
      Post::orderBy('views')->orderByDefault()->get();
      
  2. Dynamic Columns:
    • Issue: Closure-based $orderByColumn may cause performance overhead if called repeatedly.
    • Fix: Cache the result or use a static value for performance-critical paths.
  3. Reserved Keywords:
    • Issue: Column names like order or asc may conflict with Laravel’s query builder.
    • Fix: Quote column names:
      protected static $orderByColumn = '"order"';
      
  4. Eager Loading:
    • Issue: Default sorting doesn’t apply to relationships in with().
    • Fix: Manually sort relationships or use local scopes.

Debugging Tips

  • Check Applied Order:
    $query = Post::toSql(); // Inspect generated SQL for ORDER BY clauses
    
  • Disable Trait: Temporarily remove use DefaultOrderBy to isolate issues.
  • Log Queries: Use Laravel’s query logging:
    DB::enableQueryLog();
    Post::all();
    dd(DB::getQueryLog());
    

Extension Points

  1. Custom Logic: Extend the trait to add pre-query hooks:
    protected static function bootDefaultOrderBy()
    {
        static::addGlobalScope(new class extends Scope {
            public function apply(Builder $builder, Model $model)
            {
                if (!$builder->getQuery()->orders) {
                    $builder->orderByDefault();
                }
            }
        });
    }
    
  2. Conditional Sorting: Use model events to dynamically set $orderByColumn:
    protected static function boot()
    {
        static::retrieved(function ($model) {
            if (auth()->check()) {
                static::$orderByColumn = 'user_id';
            }
        });
    }
    
  3. Database-Level Defaults: For MySQL, set table-level defaults:
    ALTER TABLE posts ORDER BY title ASC;
    
    (Note: This is database-specific and may not work with all setups.)

Configuration Quirks

  • Published Config: The package publishes a config file, but it’s primarily for global fallbacks. Model-level properties ($orderByColumn) take precedence.
  • Caching: If using dynamic columns, ensure your caching layer (e.g., Redis) doesn’t cache stale column names.
  • Testing: Reset static properties in tests:
    Post::resetOrderByColumn();
    
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium