In my database, I have a table of items, sorted by a numeric "position" column. Each position is unique, and they define how the data is displayed (1 is displayed first, and 10 is displayed last, for example).
I'm trying to write out a controller that allows me to do two key things:
Firstly, I need to be able to move any item up one place or down one place (obviously if it's at the beginning or end already, it can't be moved up or down, respectively).
Secondly, I would like to be able to reorder the items using a drag and drop interface. I've found such interfaces, but I don't know how to use one.
If you've ever successfully implemented a reordering feature for a table, whether it uses drag and drop or "up" and "down" buttons, please help me! This is proving very, very complicated, and yet it's very important to my website. I'm not exactly a newbie to Laravel, it's just I underestimated how hard it was to do this!
I just tackled the exact same issue. I will tear down how I handled it.
For the client side, I used this library.
Javascript:
$( document ).ready(function() {
$("#table-categories").rowSorter({
onDrop: function(tbody, row, new_index, old_index) {
$.post("/path/to/api/priority", {old_index: old_index + 1, new_index: new_index + 1, _token: "<?php echo csrf_token(); ?>" }, function(result){
console.log('server result: ' + result);
});
},
});
});
Mind the +1's on old_index
and new_index
because I am not overwriting the row indexes on the rowsorter library, yet my priority
index on model starts from 1, not 0. If you start it from 0, just send the indexes as they are.
Server Side (Laravel Controller):
public function priority()
{
$old = \Input::get('old_index');
$new = \Input::get('new_index');
foreach (\App\Category::all() as $category)
{
if ($category->priority == $old)
{
$category->priority = $new;
$category->save();
}
else
{
if ($old < $new)
{
if ($category->priority <= $new AND $category->priority >= $old)
{
$category->priority -= 1;
$category->save();
}
}
else
{
if ($category->priority <= $old AND $category->priority >= $new)
{
$category->priority += 1;
$category->save();
}
}
}
}
return 'OK';
}
Note: Only implementation missing about this logic is tackling the priority when a row is inserted or deleted from the table, remember to implement them. If you have issues doing that, let me know so I can add the implementation.