Reputation: 1007
Below is my code which I have written to delete data from MySql using laravel but I am facing a problem while deleting; which is it always delete the top most row; regardless of which row I clicked.
<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>
Here is my controller file:
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");
}
Upvotes: 0
Views: 76
Reputation: 687
It's because of you define same ID for all your fomrs.
You can define unique form id by adding POST ID at the end of it.
So, your code would be:
<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>
Upvotes: 1
Reputation: 14268
The problem you are facing is because you are referencing to the same form every single time. ID in HTML is unique for an element, and it will always reference to one element randomly in your case always the first element with that ID on the page.
A better approach would be to have the url for each element in the anchor tag:
<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
">
and have one <form>
element in your view:
<form id="delete-form" action="" method="post" style="display:none;" >
<input type="hidden" name="_method" value="delete" >
{{csrf_field()}}
</form>
Upvotes: 0