Laravel API DELETE request
Making a DELETE request to a Laravel API using JavaScript's Fetch API allows you to remove existing resources from your application. Here’s a detailed guide on how to achieve this.
Step-by-Step Guide to Making a DELETE Request
1. Set Up the Laravel API
First, ensure that your Laravel API can handle DELETE requests.
Define the Route:
In routes/api.php
, add a route for deleting an existing user:
use App\Http\Controllers\UserController;
Route::delete('/users/{id}', [UserController::class, 'destroy']);
Create the Controller Method:
In UserController.php
, implement the destroy
method to handle the incoming request and delete a user:
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function destroy($id)
{
// Find user by ID
$user = User::findOrFail($id);
// Delete user
$user->delete();
return response()->json(['message' => 'User deleted successfully.'], 200); // Return success message
}
}
2. Create the Frontend with JavaScript Fetch API
You will create a simple interface to collect the user ID of the resource you want to delete and send it to your Laravel API using the Fetch API.
HTML Form:
Here’s an example HTML form to delete a user:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Delete User</title>
</head>
<body>
<h1>Delete User</h1>
<form id="user-delete-form">
<label for="id">User ID:</label>
<input type="number" id="id" required><br>
<button type="submit">Delete User</button>
</form>
<div id="response-message"></div>
<script src="app.js"></script> <!-- Link to your JavaScript file -->
</body>
</html>
JavaScript Fetch DELETE Request:
In a file named app.js
, implement the JavaScript to handle the form submission and make the DELETE request
document.addEventListener('DOMContentLoaded', () => {
const form = document.getElementById('user-delete-form');
const responseMessage = document.getElementById('response-message');
form.addEventListener('submit', (event) => {
event.preventDefault(); // Prevent the default form submission
// Gather user ID
const userId = document.getElementById('id').value;
// Make a DELETE request to the API
fetch(`http://your-app.test/api/users/${userId}`, { // Replace with your API URL
method: 'DELETE',
headers: {
'Content-Type': 'application/json', // Specify JSON content type
}
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json(); // Parse JSON response
})
.then(data => {
responseMessage.textContent = data.message; // Display success message
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
responseMessage.textContent = 'Error: ' + error.message; // Display error message
});
});
});
3. Handling CORS (Cross-Origin Resource Sharing)
If your Laravel API and frontend are running on different origins (different domains or ports), you might encounter CORS issues. To enable CORS in Laravel, you can use the Laravel CORS package.
You can install it via Composer if it isn't already included in your project:
composer require fruitcake/laravel-cors
After installing, configure the CORS settings in config/cors.php
to allow requests from your frontend's origin.
Summary
In this guide, you learned how to:
- Set up a Laravel API endpoint to handle DELETE requests for removing an existing user.
- Create a simple HTML form to collect the user ID for deletion.
- Use JavaScript's Fetch API to send the DELETE request to the Laravel API and handle the response.
This process allows for easy resource management in your Laravel application, enabling the deletion of items dynamically and providing user feedback.