问题
I am new to Laravel framework but I really like it. My biggest problem is I have been searching on how I can delete a single record using resource controller.
Controller method:
public function destroy($id) {
$department = Department::find($id);
$department->delete();
}
Delete link I have tried:
<a class="btn btn-xs btn-danger" data-method="delete" href="{{ URL::to('department/' . $department->id) }}"><i class="icon-remove"></i></a>
Javascript:
<script type="text/javascript">
$(function(){
$('[data-method]').append(function(){
return "\n" +
"form action='" + $(this).attr('href') + "' method='post' style='display: none;'>\n" +
"<input type='hidden' name='_method' value='"+$(this).attr('data-method')+"'>\n" +
"</form>\n"
})
.removeAttr('href')
.attr('style', 'cursor: pointer;')
.attr('onclick', '$(this).find("form").submit();');
});
Now when I click on the delete link, it doesn't work. Any idea on what am I doing wrong, I have been searching for so long.
回答1:
Use $.post() to trigger your click instead of that form creation/submission:
$(document).on("click", "[data-method]", function(e) {
e.preventDefault();
$.post($(this).attr('href'), {/* the id goes here */});
});
Apply the cursor style via CSS. I must admit that I'm not sure if laravel expects a HTTP DELETE instead of a post. And I think you missed to submit the id of the department you want to delete.
[edit] As laravel expects a HTTP DELETE you can't use the $.post() shorthand, but $.ajax() instead:
$(document).on("click", "[data-method]", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('href'),
type: "DELETE",
data: {/* the id goes here */},
success: function(data, textStatus, jqXHR) {
console.log("success");
}
});
});
回答2:
The destroy()
will be called in DELETE
request and not in POST
request.
So try ,
<a class="btn btn-xs btn-danger" onclick="deleteDepartment($department->id)" href="javascript:void(0)"><i class="icon-remove"></i></a>
And in javascript,
function deleteDepartment(id) {
$.ajax({
url: 'department/'+id,
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
}
回答3:
Thanks for the answers guys, it works just as it is I just forgot the opening < when creating a form ie I was mistakenly wrote:
"form action='" + $(this).attr('href') + "' method='post' style='display: none;'>\n" +
Instead of:
"<form action='" + $(this).attr('href') + "' method='post' style='display: none;'>\n" +
来源:https://stackoverflow.com/questions/19167762/laravel-4-restful-delete-a-record-with-a-resource-controller