PHP code example of nevadskiy / laravel-position

1. Go to this page and download the library: Download nevadskiy/laravel-position library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nevadskiy / laravel-position example snippets




namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Nevadskiy\Position\HasPosition;

class Category extends Model
{
    use HasPosition;
}

Schema::create('categories', function (Blueprint $table) {
    $table->integer('position')->unsigned()->index();
});

$category = Category::create();
echo $category->position; // 0

$category = Category::create();
echo $category->position; // 1

$category = Category::create();
echo $category->position; // 2

public function getStartPosition(): int
{
    return 1;
}

public function getNextPosition(): int
{
    return $this->getStartPosition();
}

$first = Category::create();
echo $first->position; // 0

$second = Category::create();
echo $second->position; // 0
echo $first->position; // 1 (automatically updated)

$third = Category::create();
echo $third->position; // 0
echo $second->position; // 1 (automatically updated)
echo $first->position; // 2 (automatically updated again)

Category::orderByPosition()->get();

public function alwaysOrderByPosition(): bool
{
    return true;
}

$category->update([
    'position' => 3
]);

$category->move(3);

$category->move(-1); // Move to the end

$category->swap($anotherCategory);

Category::arrangeByKeys([3, 5, 7]);

public function groupPositionBy(): array
{
    return [
        'category_id',
    ];
}

use Nevadskiy\Position\PositionObserver;

PositionObserver::lockFor(Category::class);

$category->update(['position' => 1]);

PositionObserver::unlockFor(Category::class);