下面是我编写的使用laravel从MySql删除数据的代码,但是删除时遇到了问题;它总是删除最上面的行;无论我点击哪一行。
<a href="/posts/{{$post->id}}/edit">Edit</a>
<a href="#" onclick="
var result = confirm('Are you Sure, You want to delete this Company?');
if(result){
document.getElementById('delete-form').submit();
}
">
Delete
<form id="delete-form" action="{{ route('posts.destroy',[$post->id]) }}" method="post" style="display:none;" >
<input type="hidden" name="_method" value="delete" >
{{csrf_field()}}
</form>
这是我的控制器文件:
public function destroy(Post $post)
{
dd($post->id); same id comes here always rregardless of which row I might click...
$findpost = Post::find($post->id);
if($findpost->delete()){
return redirect('/posts')->with('success','Post Removed Successfully') ;
}
return back()->withinput()->with('error',"Company Post be deleted");
}
答案 0 :(得分:1)
这是因为您为所有角色定义了相同的ID。
您可以通过在表单ID的末尾添加POST ID来定义唯一的表单ID。
因此,您的代码应为:
<a href="/posts/{{$post->id}}/edit">Edit</a>
<a href="#" onclick="
var result = confirm('Are you Sure, You want to delete this Company?');
if(result){
document.getElementById('delete-form{{$post->id}}').submit();
}
">
Delete
<form id="delete-form{{$post->id}}" action="{{ route('posts.destroy',[$post->id]) }}" method="post" style="display:none;" >
<input type="hidden" name="_method" value="delete" >
{{csrf_field()}}
</form>
答案 1 :(得分:0)
您面临的问题是因为您每次都引用相同的表单。 HTML中的ID对于一个元素是唯一的,在您的情况下,它将始终随机引用一个元素,始终是页面上具有该ID的第一个元素。
更好的方法是在锚标记中包含每个元素的网址:
<a href="{{ route('posts.destroy',[$post->id]) }}" onclick="
var result = confirm('Are you Sure, You want to delete this Company?');
if(result){
document.getElementById('delete-form').setAttribute("action", this.href).submit();
}
return false; // to prevent submitting the form on click before the alert is displayed
">
并在您的视图中包含一个<form>
元素:
<form id="delete-form" action="" method="post" style="display:none;" >
<input type="hidden" name="_method" value="delete" >
{{csrf_field()}}
</form>