PHPackages                             alik-laravel/ordering - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. alik-laravel/ordering

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

alik-laravel/ordering
=====================

Laravel package for ordering functionality

1.0.0(8mo ago)072↓50%MITPHPPHP ^8.2

Since Sep 17Pushed 8mo agoCompare

[ Source](https://github.com/alik-laravel/ordering)[ Packagist](https://packagist.org/packages/alik-laravel/ordering)[ Docs](https://github.com/alik-laravel/ordering)[ RSS](/packages/alik-laravel-ordering/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (9)Versions (2)Used By (0)

Laravel Ordering
================

[](#laravel-ordering)

[![Latest Version on Packagist](https://camo.githubusercontent.com/b234f18e368ef7a7ce335e0494652b89ad8e27fd17a1d4900f766caf2db80581/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f616c696b2d6c61726176656c2f6f72646572696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/alik-laravel/ordering)[![Tests](https://camo.githubusercontent.com/5067633f8ced2189ae52b21b8129ac96996f2b159135caa1d321bbee0bdc8934/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f616c696b2d6c61726176656c2f6f72646572696e672f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/alik-laravel/ordering/actions/workflows/run-tests.yml)[![Total Downloads](https://camo.githubusercontent.com/b9d73a8e0682a9f04c0a1752d6050921f19f8c62b7fee9b26f8af8e2c3be59f0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f616c696b2d6c61726176656c2f6f72646572696e672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/alik-laravel/ordering)

A simple Laravel package that provides ordering functionality for Eloquent models. Add the `HasOrdering` trait to any model to automatically handle ordering with scope support.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require alik-laravel/ordering
```

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 10.0+ or 11.0+

Usage
-----

[](#usage)

### 1. Add the trait to your model

[](#1-add-the-trait-to-your-model)

```
use Alik\Ordering\HasOrdering;
use Illuminate\Database\Eloquent\Model;

class MenuItem extends Model
{
    use HasOrdering;

    protected $fillable = ['name', 'order', 'category_id'];

    /**
    * @return array
    */
    protected function casts(): array
    {
      return [
        'order' => 'float',
      ];
    }
}
```

### 2. Add an `order` column to your migration

[](#2-add-an-order-column-to-your-migration)

```
Schema::create('menu_items', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->float('order')->default(0);
    $table->unsignedBigInteger('category_id')->nullable();
    $table->timestamps();
});
```

### 3. Automatic ordering

[](#3-automatic-ordering)

Models with the `HasOrdering` trait will:

- Automatically be ordered by the `order` column
- Get the next available order value when created
- Provide methods for reordering

```
// Models are automatically ordered
$items = MenuItem::all(); // Ordered by 'order' column ASC

// New models get the next order automatically
$newItem = MenuItem::create(['name' => 'New Item']); // order = last_order + 1
```

### 4. Manual ordering operations

[](#4-manual-ordering-operations)

```
// Get an Orderer instance for positioning
$item = MenuItem::find(1);
$orderer = $item->ordering();

// Calculate positions
$beforePosition = $orderer->before(); // Position before current item
$afterPosition = $orderer->after();   // Position after current item
$firstPosition = $orderer->first();   // First position
$lastPosition = $orderer->last();     // Last position

// Reorder all items (fixes gaps in ordering)
MenuItem::reorder();

// Reorder within a scope (e.g., same category)
MenuItem::reorderWithinScope(['category_id' => 1]);
```

### 5. Scoped ordering

[](#5-scoped-ordering)

You can work with ordering within specific scopes:

```
// Get orderer for items within the same category
$orderer = $item->ordering(['category_id' => $item->category_id]);

// Reorder only items with category_id = 1
MenuItem::reorderWithinScope(['category_id' => 1]);

// Handle null values in scope
MenuItem::reorderWithinScope(['parent_id' => null]);
```

### 6. Controller implementation for drag-and-drop

[](#6-controller-implementation-for-drag-and-drop)

Here's how to implement a controller action to handle drag-and-drop reordering from a frontend component:

```
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class MenuItemController extends Controller
{
    public function updateOrder(Request $request)
    {
        $validated = $request->validate([
            'position' => ['required', Rule::in(['before', 'after'])],
            'source_id' => ['required', 'integer', 'exists:menu_items,id'],
            'target_id' => ['required', 'integer', 'exists:menu_items,id'],
        ]);

        $source = MenuItem::findOrFail($validated['source_id']);
        $target = MenuItem::findOrFail($validated['target_id']);
        $position = $validated['position'];

        // Optional: Add scope validation if needed
        // if ($source->category_id !== $target->category_id) {
        //     return response()->json(['error' => 'Items must be in same category'], 422);
        // }

        // Update the source item's order based on target position
        $source->update([
            'order' => $target->ordering()->$position()
        ]);

        return response()->json(['success' => true]);
    }
}
```

#### Frontend JavaScript example

[](#frontend-javascript-example)

```
// When drag-and-drop completes, send the update request
function updateItemOrder(sourceId, targetId, position) {
    fetch('/menu-items/update-order', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
        },
        body: JSON.stringify({
            source_id: sourceId,
            target_id: targetId,
            position: position // 'before' or 'after'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            console.log('Order updated successfully');
        }
    });
}
```

#### With scoped ordering

[](#with-scoped-ordering)

If you need to maintain ordering within a specific scope (e.g., same category):

```
public function updateOrder(Request $request)
{
    $validated = $request->validate([
        'position' => ['required', Rule::in(['before', 'after'])],
        'source_id' => ['required', 'integer', 'exists:menu_items,id'],
        'target_id' => ['required', 'integer', 'exists:menu_items,id'],
    ]);

    $source = MenuItem::findOrFail($validated['source_id']);
    $target = MenuItem::findOrFail($validated['target_id']);
    $position = $validated['position'];

    // Ensure items are in the same scope
    if ($source->category_id !== $target->category_id) {
        return response()->json(['error' => 'Items must be in same category'], 422);
    }

    // Use scoped ordering
    $scopeAttributes = ['category_id' => $target->category_id];
    $source->update([
        'order' => $target->ordering($scopeAttributes)->$position()
    ]);

    return response()->json(['success' => true]);
}
```

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

Run tests with coverage:

```
composer test-coverage
```

Code Quality
------------

[](#code-quality)

Format code with Laravel Pint:

```
composer format
```

Run static analysis with Larastan:

```
composer analyse
```

Refactor code with Rector:

```
composer refactor
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Aleksandr Manukyan](https://github.com/alik-laravel)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance62

Regular maintenance activity

Popularity11

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

243d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/85644385?v=4)[amanukian](/maintainers/amanukian)[@amanukian](https://github.com/amanukian)

---

Top Contributors

[![alikmanukian](https://avatars.githubusercontent.com/u/4147821?v=4)](https://github.com/alikmanukian "alikmanukian (1 commits)")

---

Tags

laravelpackageordering

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/alik-laravel-ordering/health.svg)

```
[![Health](https://phpackages.com/badges/alik-laravel-ordering/health.svg)](https://phpackages.com/packages/alik-laravel-ordering)
```

###  Alternatives

[bensampo/laravel-embed

Painless responsive embeds for videos, slideshows and more.

142146.8k](/packages/bensampo-laravel-embed)[okipa/laravel-table

Generate tables from Eloquent models.

56752.8k](/packages/okipa-laravel-table)[erlandmuchasaj/laravel-gzip

Gzip your responses.

40129.3k2](/packages/erlandmuchasaj-laravel-gzip)[gallib/laravel-short-url

A Laravel package to shorten urls

16516.4k](/packages/gallib-laravel-short-url)[hydrat/filament-table-layout-toggle

Filament plugin adding a toggle button to tables, allowing user to switch between Grid and Table layouts.

6292.3k1](/packages/hydrat-filament-table-layout-toggle)[ralphjsmit/laravel-helpers

A package containing handy helpers for your Laravel-application.

13704.6k2](/packages/ralphjsmit-laravel-helpers)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
