Reputation: 94
I am new to laravel and was facing a problem. I have made a delete function in Controller and added it in the route properly. Then I connected it to a button in the view. When I press the button, it redirects me to the same page without deleting anything.
Here's my function :
public function delete_user($id){
$data = User::where('id' , $id);
$data->delete();
return route('home');
}
Here's my route :
Route::get('/delete/user/{id}' , 'UserController@delete_user');
I am adding it in view like this :
<a href="{{action('UserController@delete_user' , $user->id)}}"><button class="btn btn-info btn-fill pull-right">Delete Profile</button></a>
After redirecting there is a ? infront of the url like abcd.com/delete/1?
When I hover over the button, it shows the correct route(bottom left corner in image), but nothing is happening when I press it :
Any help would be appreciated. Thanks
EDIT : The same function works perfectly fine in another view instance.
Upvotes: 0
Views: 1325
Reputation: 94
After some experimentation it seems that I made a rather careless mistake. I was deleting as a form submit type. I just took the button outside the form and it worked perfectly.
Upvotes: 0
Reputation: 510
try this:
public function delete_user($id){
$data = User::where('id' , $id)->first();
// or
// $data = User::find($id);
$data->delete();
return route('home');
}
Whenever you use the where
clause to retrieve a single resource you have to call first()
or get()
for a collection.
Try doing it this way:
Controller method
public function delete_user($id){
$user = User::findOrFail($id);
$user->delete();
return route('home');
}
Route
Route::delete('/delete/user/{id}' , 'UserController@delete_user')->name('delete-user');
View
<a class="btn btn-info btn-fill pull-right" href="{{ route('delete-user') }}"
onclick="event.preventDefault();
document.getElementById('delete-user').submit();">
{{ __('Delete user') }}
</a>
<form id="delete-user" action="{{ route('delete-user') }}" method="POST" style="display: none;">
@csrf
</form>
Also I think <a href="{{action('UserController@delete_user' , $user->id)}}"><button class="btn btn-info btn-fill pull-right">Delete Profile</button></a>
should be problematic because you have a button inside a link...its wrong. If you want to use button the the approach I just showed you is better. but really your link should look like:
<a href="{{ url("/delete/user/{$user->id}")}}">Delete Profile</a>
Upvotes: 1
Reputation: 692
you need to modify your delete function inside controller like below...
public function delete_user($id){
$data = User::find($id);
$data->delete();
return redirect('/home'); //write name of view where you want to go.
}
Upvotes: 1