I'm building a blog in Laravel v5.2 just to learn the system. I wanted to use jQuery UI Sortable. However whenever I try and sort the list it returns "POST http://localhost:3000/posts/reposition 500 (Internal Server Error)" in Chrome's console.
I took a look at jQuery UI Sortable, then write order into a database however I still cannot get it to work.
I'm looking to either see why I'm getting (Internal Server Error). I'm new to Laravel and not sure if my update method is wrong or if I'm just totally doing it wrong.
Thanks in advance!
Here is my code:
Controller:
public function sort($cat_id)
{
$posts = DB::table('posts')->where('category_id', '=', $cat_id)->orderBy('position', 'ASC')->get();
return view('posts.sort')->with('posts', $posts)->with('cat_id', $cat_id);
}
public function reposition()
{
$i = 0;
foreach ($_POST['item'] as $value) {
// Execute statement:
// UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
$i++;
DB::table('posts')->where('id', '=', $value)->update([ 'position' => $i ]);
}
}
View:
<ul class='sort-post-list' style="list-style:none;">
@foreach($posts as $post)
<li id="item-{{ $post->id }}">{{ $post->title }}</li>
@endforeach
</ul>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$('.sort-post-list').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '{{ route('posts.reposition') }}'
});
}
});
</script>
Outputted HTML:
<ul class='sort-post-list' style="list-style:none;">
<li id="item-1">Introduction and Approach to Materials</li>
<li id="item-2">Teaching Philosophy</li>
<li id="item-3">Acknowledgements</li>
</ul>
<script>
$('.sort-post-list').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '//localhost:3000/posts/reposition'
});
}
});
</script>
Routes:
Route::get('posts/sort/{cat_id}', [ 'uses' => 'PostController@sort', 'as' => 'posts.sort' ]);
Route::post('posts/reposition', [ 'uses' => 'PostController@reposition', 'as' => 'posts.reposition' ]);