I have a delete link that links to destroy button
<i class="icon-trash"></i>
<a style="color:black" href="route{{ action('TasksController@destroy', ['id' => $task->id ,'method'=>'DELETE'] ) }}">
delete
</a>
This is the destroy function
public function destroy($id)
{
//delete task
$task = Task::find($id);
$task->delete();
return redirect('/home')->with('success', 'Task deleted successfully');
}
but the link is not working when clicked
The Blade
syntax is incorrect, change it to:
<i class="icon-trash"></i>
<a style="color:black" href="{{ route('tasks.destroy', ['id' => $task->id]) }}">
delete
</a>
Which requires a route like this:
Route::get('/tasks/delete/{id}', 'TasksController@destroy')
->name('tasks.destroy');
And a controller method like this:
public function destroy($id)
{
// delete task
$task=Task::find($id);
$task->delete();
return redirect('/home')->with('success','Task deleted successfully');
}
Having a get method to delete is a security vulnerability as anyone can trick other users into deleting tasks just by providing a link
Here are some suggestions to improve your code
Change your HTML to perform a post request:
<i class="icon-trash"></i>
<a style="color:black"
href="{{ route('tasks.destroy', ['task' => $task]) }}"
onclick="event.preventDefault();
document.getElementById('delete-form-{{ $task->id }}').submit();">
delete
</a>
<form id="delete-form-{{ $task->id }}" action="{{ route('tasks.destroy', ['task' => $task]) }}"
method="POST" style="display: none;">
@csrf
</form>
And the route to DELETE
with route model binding:
Route::delete('/tasks/delete/{task}', 'TasksController@destroy')
->name('tasks.destroy');
You can add dependency injection to the controller method like this:
public function destroy(Task $task)
{
// delete task
$task->delete();
return redirect('/home')->with('success','Task deleted successfully');
}