Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save placidrod/69f4333abb31ae5b944164c3f7f6d693 to your computer and use it in GitHub Desktop.
Save placidrod/69f4333abb31ae5b944164c3f7f6d693 to your computer and use it in GitHub Desktop.
Laravel Restful jQuery Ajax Delete Record
// route: route must go through 'web' middleware
Route::group(['middleware' => ['web']], function () {
Route::resource('post', 'PostsController');
});
// view: href link with token
<a href="{{ action('PostsController@destroy', ['id'=>$post->id]) }}"
data-token="{{ csrf_token() }}"
data-id="{{ $post->id }}"
class="delete-post-link"
>Delete
</a>
// js:
$('.delete-post-link').on('click', function(e) {
e.preventDefault();
var parentPost = $(this).closest('.post');
$.ajax({
method : 'delete',
url : $(this).attr('href'),
data : {
_token : $(this).data('token')
},
success : function(data) {
if(data === 'delete success') {
// location.reload();
parentPost.slideUp();
} else {
alert("Could not delete data");
}
},
error: function (error) {
console.log(error);
}
});
});
// controller destroy method
public function destroy(Post $post, Request $request)
{
if($request->ajax()) {
if($post->delete()) {
return "delete success";
} else {
return "delete failed";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment