ebess/eloquent-sortable-relations

Add sortable relations to laravel eloquent ORM

dev-master 2019-09-19 11:07 UTC

README

Build Status codecov

Motivation

This package makes it easy to sort relations. You could achieve the same result by ordering by columns manually. By using this package you have a convenient drop-in solution.

Install

composer require ebess/eloquent-sortable-relations

Add field to your models

Add a nullable json relation_order field to your model and pivot tables.

HasMany|MorphMany relations

Schema::create('posts', function (Blueprint $table) {
    $table->bigIncrements('id');
    
    $table->bigInteger('user_id')->unsigned()->nullable();
    $table->foreign('user_id')->references('id')->on('users');
    
    // add this field 
    $table->json('relation_order')->nullable();
});

BelongsToMany|MorphToMany relations

Schema::create('post_user', function (Blueprint $table) {
    $table->bigIncrements('id');
    
    $table->bigInteger('user_id')->unsigned()->nullable();
    $table->foreign('user_id')->references('id')->on('users');

    $table->bigInteger('post_id')->unsigned()->nullable();
    $table->foreign('post_id')->references('id')->on('posts');
    
    // add this field 
    $table->json('relation_order')->nullable();
});

Usage

Set order on the relation

// pass primary keys
$user->posts()->setOrder([3,2,1]);

// pass models
$user->posts()->setOrder([User::find(3), User::find(2), User::find(1)]);

Sort relation

$user->posts()->sorted()->get(); // Model(3), Model(2), Model(1) 

Sort relation by default

class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class)->sorted();
    }
}