Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CRUD Laravel 5 how to link to destroy of Resource Controller?

I have a link

<a class="trashButton" href="{{ URL::route('user.destroy',$members['id'][$i]) }}" style="cursor: pointer;"><i class="fa fa-trash-o"></i></a>  

this link is supposed to direct to the destroy method of the Usercontroller , this is my route Route::resource('/user', 'BackEnd\UsersController');

UserController is a Resource Controller. But at this moment it is directing me to the show method rather than directing to the destroy method

like image 632
xenish Avatar asked May 18 '15 09:05

xenish


2 Answers

You need to send a DELETE request instead of a GET request. You can't do that with a link, so you have to use an AJAX request or a form.

Here is the generic form method:

<form action="{{ URL::route('user.destroy', $members['id'][$i]) }}" method="POST">     <input type="hidden" name="_method" value="DELETE">     <input type="hidden" name="_token" value="{{ csrf_token() }}">     <button>Delete User</button> </form> 

If you're using Laravel 5.1 or later then you can use Laravel's built-in helpers to shorten your code:

<form action="{{ route('user.destroy', $members['id'][$i]) }}" method="POST">     {{ method_field('DELETE') }}     {{ csrf_field() }}     <button>Delete User</button> </form> 

If you're using Laravel 5.6 or later then you can use the new Blade directives to shorten your code even further:

<form action="{{ route('user.destroy', $members['id'][$i]) }}" method="POST">     @method('DELETE')     @csrf     <button>Delete User</button> </form> 

You can read more about method spoofing in Laravel here.

like image 189
BrokenBinary Avatar answered Oct 23 '22 17:10

BrokenBinary


This is because you are requesting the resources via GET method instead DELETE method. Look:

DELETE  /photo/{photo}  destroy     photo.destroy GET     /photo/{photo}  show    photo.show 

Both routes have the same URL, but the header verb identifies which to call. Looks the RESTful table. For example, via ajax you can send a DELETE request:

$.ajax({     url: '/user/4',     type: 'DELETE',  // user.destroy     success: function(result) {         // Do something with the result     } }); 
like image 42
manix Avatar answered Oct 23 '22 17:10

manix