首页 >后端开发 >php教程 >Laravel API中的资源响应自定义

Laravel API中的资源响应自定义

Robert Michael Kim
Robert Michael Kim原创
2025-03-05 15:22:14460浏览

Resource Response Customization in Laravel APIs

Laravel's

方法提供了增强API响应的强大方法。 它使您可以在发送给客户端之前修改HTTP响应对象,超越简单的数据调整,以包含标头,状态代码和其他响应属性。withResponse>

这对于构建需要传达元数据,版本详细信息或自定义标题的强大API特别有用。

>

这是一个基本示例:

class UserResource extends JsonResource
{
    public function withResponse($request, $response)
    {
        $response->header('X-Resource-Type', 'User');
    }
}
此示例演示了更全面的API响应自定义:>

>通过利用
<?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');
        }
    }
}
方法,您的API资源从单纯的数据持有器演变为完全可自定义的HTTP响应,并在核心数据旁边用必需的元数据丰富您的API。

以上是Laravel API中的资源响应自定义的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn