Laravel - API Resources - Resource Responses

As you have already read, resources may be returned directly from routes and controllers:

    
    use App\Http\Resources\UserResource;
    use App\Models\User;
    
    Route::get('/user/{id}', function ($id) {
        return new UserResource(User::findOrFail($id));
    });
	

However, sometimes you may need to customize the outgoing HTTP response before it is sent to the client. There are two ways to accomplish this. First, you may chain the response method onto the resource. This method will return an Illuminate\Http\JsonResponse instance, giving you full control over the response's headers:

    
    use App\Http\Resources\UserResource;
    use App\Models\User;
    
    Route::get('/user', function () {
        return (new UserResource(User::find(1)))
                    ->response()
                    ->header('X-Value', 'True');
    });
	

Alternatively, you may define a withResponse method within the resource itself. This method will be called when the resource is returned as the outermost resource in a response:

    
     $this->id,
            ];
        }
    
        /**
         * Customize the outgoing response for the resource.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Illuminate\Http\Response  $response
         * @return void
         */
        public function withResponse($request, $response)
        {
            $response->header('X-Value', 'True');
        }
    }