Laravel API POST request


Making a POST request to a Laravel API using JavaScript's Fetch API involves a few steps similar to a GET request, but with additional considerations for sending data to the server. Here's a comprehensive guide to achieving this.

Step-by-Step Guide to Making a POST Request

1. Set Up the Laravel API

First, you need to ensure that your Laravel API can handle POST requests.

Define the Route:

In routes/api.php, add a route for creating a new user:

use App\Http\Controllers\UserController; Route::post('/users', [UserController::class, 'store']);

Create the Controller Method:

In UserController.php, implement the store method to handle the incoming request and create a new user:

namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; class UserController extends Controller { public function store(Request $request) { // Validate incoming request $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:8', ]); // Create a new user $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => bcrypt($request->password), // Hash the password ]); return response()->json($user, 201); // Return created user with 201 status } }

2. Create the Frontend with JavaScript Fetch API

You will create a simple form on your frontend to collect user data and send it to your Laravel API using the Fetch API.

HTML Form:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Create User</title> </head> <body> <h1>Create User</h1> <form id="user-form"> <label for="name">Name:</label> <input type="text" id="name" required><br> <label for="email">Email:</label> <input type="email" id="email" required><br> <label for="password">Password:</label> <input type="password" id="password" required><br> <button type="submit">Submit</button> </form> <div id="response-message"></div> <script src="app.js"></script> <!-- Link to your JavaScript file --> </body> </html>

JavaScript Fetch POST Request:

In a file named app.js, implement the JavaScript to handle the form submission and make the POST request:

document.addEventListener('DOMContentLoaded', () => { const form = document.getElementById('user-form'); const responseMessage = document.getElementById('response-message'); form.addEventListener('submit', (event) => { event.preventDefault(); // Prevent the default form submission // Gather form data const formData = { name: document.getElementById('name').value, email: document.getElementById('email').value, password: document.getElementById('password').value }; // Make a POST request to the API fetch('http://your-app.test/api/users', { // Replace with your API URL method: 'POST', headers: { 'Content-Type': 'application/json', // Specify JSON content type }, body: JSON.stringify(formData) // Convert form data to JSON }) .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 = `User created: ${data.name} (${data.email})`; // 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 POST requests for creating a new user.
  • Create a simple HTML form to gather user input.
  • Use JavaScript's Fetch API to send the form data to the Laravel API and handle the response.

This process allows for easy integration between your Laravel backend and frontend, enabling the creation of new resources dynamically.