Created
April 2, 2016 06:29
-
-
Save placidrod/69f4333abb31ae5b944164c3f7f6d693 to your computer and use it in GitHub Desktop.
Laravel Restful jQuery Ajax Delete Record
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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