I'm using Laravel and I'm trying to achieve a delete function that takes care of deleting the selected task the user made.
I was wondering how can I achieve this using routes?
<a href="{{ route("tasks.edit", ["id" => $task->id]) }}"><button class="btn btn-outline-light">Edit</button></a>
<a href="{{ route("tasks.destroy", ["id" => $task->id]) }}"><button class="btn btn-outline-light">Delete</button></a>
At this moment my delete route takes me to the same page as what the edit route does.
My delete function:
public function destroy(Task $task)
{
$task->delete();
return redirect('/tasks')->with('success', 'Task removed');
}
I got a working delete function using the Laravel forms:
{!! Form::open(['action' => ['TasksController@destroy', $task->id], 'method' => 'POST', 'class'=> 'float-right']) !!}
{{Form::hidden('_method','DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-outline-danger'])}}
{!! Form::close() !!}
Is it worth to consider another method of taking care of my deletes or should I stick with using the Laravel forms?
That's because of CSRF protection. You may think using an ajax request. You can find an example in this post. How to delete record in laravel 5.3 using ajax request?
When you press the delete link, you'll be basically making a GET request to the tasks.destroy route, which is not what you want. You can either create a form and submit it on click (the laravel logout btn does something similar)
<a href="#"
onclick="event.preventDefault(); document.getElementById('task-destroy-form').submit();">
Delete task
</a>
<form id="task-destroy-form" action="{{ route("tasks.destroy", ["id" => $task->id]) }}" method="POST" style="display: none;">
{{ csrf_field() }}
<input type="hidden" name="_method" value="DELETE">
</form>
or make an ajax call that will send the id and CSRF parameters to the route.