How to handle delete request in laravel?

by lindsey.homenick , in category: PHP Frameworks , a year ago

How to handle delete request in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , a year ago

@lindsey.homenick 

To handle a delete request in Laravel, follow these steps:

  1. Define a route for the delete request in web.php or api.php file. For example, you can add the following route:
1
Route::delete('/delete/{id}', 'YourController@delete')->name('delete');


  1. In your controller, create the delete method to handle the delete request. You can use the destroy method to delete the record. For example:
1
2
3
4
5
6
7
public function delete($id)
{
    YourModel::destroy($id);

    // Optionally, you can redirect or return a response
    return redirect()->route('your.route.name');
}


  1. In your view or form, create a form to send the delete request. For example:
1
2
3
4
5
<form action="{{ route('delete', $yourModel->id) }}" method="POST">
    @csrf
    @method('DELETE')
    <button type="submit">Delete</button>
</form>


Make sure to specify the correct method (DELETE) and the route name when creating the form.

  1. When you submit the form, Laravel will route the delete request to the delete method in your controller. The record with the specified ID will be deleted using the destroy method, and you can redirect or return a response if needed.