Php – 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

Best Solution

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>

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>

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">
    <button>Delete User</button>

You can read more about method spoofing in Laravel here.

Related Question