DEV Community

Hamza Sehouli
Hamza Sehouli

Posted on

Handling PATCH and PUT Requests with Next.js and Laravel

When building modern web apps, it’s super important to handle API requests properly. In this tutorial, we’re going to take a look at how to manage PATCH and PUT requests in a Laravel API and integrate them seamlessly with a Next.js frontend.

PATCH and PUT are both ways to update resources, but they do different things. PATCH is used for partial updates (only updating the fields that change), while PUT is typically used for full updates (replacing the entire resource). This guide will show you how to use these methods in a Next.js app that talks to a Laravel backend.

You may wonder why we just use POST to update resources, but doing that would go against the usual RESTful practices. POST is usually used to create new resources, not modify existing ones. Using PUT or PATCH makes sure your API follows the HTTP standard, giving you clear and predictable behaviors.

Setting Up Laravel for PATCH and PUT Requests

To begin, let’s explore how you can configure your Laravel backend to handle PATCH and PUT requests.

1-Step: Define Routes in api.php
In your routes/api.php, you need to define the routes that will handle the PATCH and PUT requests.

// PATCH Request - Partial update of a project
Route::patch('/projects/{id}', [ProjectController::class, 'update']);

// PUT Request - Full update of a project
Route::put('/projects/{id}', [ProjectController::class, 'update']);

2-Step: Controller Method
In your ProjectController, you’ll define the logic for handling these requests. Laravel makes it simple to handle both types of updates by using validation and updating logic.

public function update(Request $request, Project $project){
  // Validation for both PATCH and PUT
  $validated = $request->validate([
    'title' => 'required|string|max:255',
    'description' => 'required|string',
    // Add other fields as necessary
  ]);

  // Update the project
  $project->update($validated);
  return response()->json(['message' => 'Project updated successfully.']);
 }
Enter fullscreen mode Exit fullscreen mode

The same update method is used for both PATCH and PUT. This is because both methods usually do the same thing: update an existing resource. The main difference is that a PATCH request updates only some parts of a resource, while a PUT replaces the resource entirely.

Handling PATCH and PUT Requests in Next.js

We’ve finished setting up the backend, so let’s focus on making the right requests from the Next.js.

1-Step: Create the Request Function
To do this, you’ll need to set up a server action to handle PATCH and PUT requests to your Laravel API. Here’s an example of how to do this in Next.js using fetch.

'use server'

export async function updateProject(initialState, formData) {
  formData.append('_method', 'PATCH'); //_method field will be used as the HTTP request method.

// Send the request to the Laravel API
  try {
    const response = await fetch(".../api/projects/id", {
      method :"POST", // We need to use the POST method to retrieve sent data in Laravel.
      body: formData // Send data
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data?.message || "Failed to update project.");
    }

    return { status: true, message: "Project updated successfully." };

  } catch (error) {
    return { status: false, message: error.message };
  }
}
Enter fullscreen mode Exit fullscreen mode

More in
https://medium.com/@sehouli.hamza/handling-patch-and-put-requests-with-next-js-and-laravel-263f62b3e647

Top comments (0)