Or you could use a trait
<?php
namespace App\Common\Models;
use DB;
trait PositionUpdate {
public static function bootPositionUpdate () {
static::created(function($item){
if (!isset($item->positionUpdateFilter)){
throw new \Exception('$item->positionUpdateFilter must be set');
}
if (!is_numeric($item->position)){
$item->position = DB::table($item->table)->max('position') + 1;
}
$sql = "UPDATE $item->table
SET position = position + 1
WHERE position >= $item->position
AND id != $item->id
AND $item->positionUpdateFilter = " . $item->{$item->positionUpdateFilter};
$update = DB::select($sql);
});
static::created(function($item){
if (!isset($item->positionUpdateFilter)){
throw new \Exception('$item->positionUpdateFilter must be set');
}
$sql = "UPDATE $item->table
SET position = position + 1
WHERE position >= $item->position
AND id != $item->id
AND $item->positionUpdateFilter = " . $item->{$item->positionUpdateFilter};
$update = DB::select($sql);
});
static::updated(function($item){
if (!isset($item->positionUpdateFilter)){
throw new \Exception('$item->positionUpdateFilter must be set');
}
if ($item->getOriginal('position') < $item->position){// move up
$sql = "
UPDATE $item->table
SET position = position - 1
WHERE id != $item->id
AND position > " . $item->getOriginal('position')."
AND position <= $item->position
AND $item->positionUpdateFilter = " . $item->{$item->positionUpdateFilter};
$update = DB::select($sql);
} else {// move down
$sql = "UPDATE $item->table
SET position = position + 1
WHERE id != $item->id
AND position >= $item->position
AND position < " . $item->getOriginal('position') . "
AND $item->positionUpdateFilter = " . $item->{$item->positionUpdateFilter};
$update = DB::select($sql);
}
});
}
}
add trait and $positionUpdateFilter to model and ensure the db table has a 'position' integer field
personally i don't recommend using traits, they are so ugly. sorry ,. my personal preference
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.