Home > Backend Development > PHP Tutorial > Resource Response Customization in Laravel APIs

Resource Response Customization in Laravel APIs

Robert Michael Kim
Release: 2025-03-05 15:22:14
Original
452 people have browsed it

Resource Response Customization in Laravel APIs

Laravel's withResponse method provides a powerful way to enhance your API responses. It lets you modify the HTTP response object before it's sent to the client, going beyond simple data adjustments to encompass headers, status codes, and other response attributes.

This is especially useful for building robust APIs that need to convey metadata, versioning details, or custom headers to clients.

Here's a basic example:

class UserResource extends JsonResource
{
    public function withResponse($request, $response)
    {
        $response->header('X-Resource-Type', 'User');
    }
}
Copy after login

This example demonstrates a more comprehensive API response customization:

<?php namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Request;

class DocumentResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'content' => $this->when(
                $request->user()->canViewContent($this->resource),
                $this->content
            ),
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at
        ];
    }

    public function withResponse(Request $request, $response)
    {
        $response->header('X-Document-ID', $this->id);

        if ($this->is_public) {
            $response->header('Cache-Control', 'public, max-age=3600');
            $response->header('ETag', md5($this->updated_at));
        }

        if ($this->wasRecentlyCreated) {
            $response->setStatusCode(201);
        }

        if ($request->has('include_legacy')) {
            $response->header('X-Deprecated-Fields', 'legacy_format,old_structure');
            $response->header('X-Deprecation-Date', '2024-07-01');
        }
    }
}
Copy after login

By leveraging the withResponse method, your API resources evolve from mere data holders into fully customizable HTTP responses, enriching your API with essential metadata alongside the core data.

The above is the detailed content of Resource Response Customization in Laravel APIs. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template