How to make a delete request with laravel?

Member

by lizzie , in category: PHP Frameworks , 6 months ago

How to make a delete request with laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dalton_moen , a month ago

@lizzie 

To make a delete request in Laravel, you can use Laravel's built-in methods and HTTP verbs. Here is an example of how to make a delete request in Laravel:

  1. Create a route in your routes/web.php file:
1
Route::delete('/posts/{id}', 'PostController@destroy');


  1. Create a controller method in your PostController:
1
2
3
4
5
6
7
public function destroy($id)
{
    $post = Post::findOrFail($id);
    $post->delete();

    return redirect('/posts')->with('success', 'Post deleted successfully');
}


  1. Create a form in your view file to trigger the delete request:
1
2
3
4
5
<form action="{{ url('/posts/'.$post->id) }}" method="POST">
    @csrf
    @method('DELETE')
    <button type="submit">Delete Post</button>
</form>


  1. When you submit the form, it will trigger the delete request and the specified post will be deleted from the database.


This is a basic example of how to make a delete request in Laravel. Remember to always use proper validation and authorization checks to ensure that only authorized users can delete records.