Skip to content

Instantly share code, notes, and snippets.

@tillsanders
Last active June 24, 2021 20:17
Show Gist options
  • Save tillsanders/39a9fa50d4c0ec36d167 to your computer and use it in GitHub Desktop.
Save tillsanders/39a9fa50d4c0ec36d167 to your computer and use it in GitHub Desktop.
Laravel: drag-and-drop repositioning with auto-save of DB entries

Laravel: drag-and-drop repositioning with auto-save of DB entries

Use case: Database entries are represented in a table. By grabbing and moving a row up or down the table, you can change the entries' order/position. The changes are submitted automatically via ajax.

  • Uses jQueryUI (custom download: sortable is needed)
  • newly created elements are added to the top (see route /jobs/create)
// head
{{ HTML::style('scripts/vendor/jquery-ui/jquery-ui.min.css') }}
// handle in each table row
<a class="handle">Move</a>
// end of body
@section('additional-scripts')
{{ HTML::script('scripts/vendor/jquery-ui/jquery-ui.min.js') }}
<script>
$('table.db tbody').sortable({
'containment': 'parent',
'revert': true,
helper: function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index) {
$(this).width($originals.eq(index).width());
});
return $helper;
},
'handle': '.handle',
update: function(event, ui) {
$.post('{{ route('jobs-reposition') }}', $(this).sortable('serialize'), function(data) {
if(!data.success) {
alert('Whoops, something went wrong :/');
}
}, 'json');
}
});
$(window).resize(function() {
$('table.db tr').css('min-width', $('table.db').width());
});
</script>
@endsection
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateJobs extends Migration {
public function up()
{
Schema::create('jobs', function($table)
{
$table->increments('id');
$table->string('profession', '256');
$table->text('description');
$table->integer('position')->unsigned();
$table->boolean('visible')->default(false);
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('jobs');
}
}
<?php
Route::post('/jobs/create', function(){
// Validation [...]
Jobs::increment('position');
$jobs = new Jobs;
// [...]
$jobs->position = 1;
$jobs->save();
return Redirect::route('home');
}
});
Route::post('/jobs/reposition', function()
{
if(Input::has('item'))
{
$i = 0;
foreach(Input::get('item') as $id)
{
$i++;
$item = Jobs::find($id);
$item->position = $i;
$item->save();
}
return Response::json(array('success' => true));
}
else
{
return Response::json(array('success' => false));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment