for testing and deploying your application
for finding and fixing issues
for empowering human code reviews
<?php
namespace A17\Twill\Models\Behaviors;
use Kalnoy\Nestedset\NodeTrait;
trait HasNesting
{
use NodeTrait;
public static function saveTreeFromIds($nodeTree)
$nodeModels = self::all();
$nodeArrays = self::flattenTree($nodeTree);
foreach ($nodeArrays as $nodeArray) {
$nodeModel = $nodeModels->where('id', $nodeArray['id'])->first();
if ($nodeArray['parent_id'] === null) {
if (!$nodeModel->isRoot() || $nodeModel->position !== $nodeArray['position']) {
$nodeModel->position = $nodeArray['position'];
$nodeModel->saveAsRoot();
}
} else {
if ($nodeModel->position !== $nodeArray['position'] || $nodeModel->parent_id !== $nodeArray['parent_id']) {
$nodeModel->parent_id = $nodeArray['parent_id'];
$nodeModel->save();
public static function flattenTree(array $nodeTree, int $parentId = null)
$nodeArrays = [];
$position = 0;
foreach ($nodeTree as $node) {
$nodeArrays[] = [
'id' => $node['id'],
'position' => $position++,
'parent_id' => $parentId,
];
if (count($node['children']) > 0) {
$childArrays = self::flattenTree($node['children'], $node['id']);
$nodeArrays = array_merge($nodeArrays, $childArrays);
return $nodeArrays;