I think Array::except might be useful here:
return Response::json([
'status' => true,
'message' => 'User Created',
'data' => Array::except($validated, ['password'])
], 200);
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I want to hide password from REST API api/v2/auth/register ?
How can i do that ?
AuthController.php
public function register(RegisterRequest $request)
{
$validated = $request->validated();
$isUserCreate = User::create($validated);
if ($isUserCreate) {
return Response::json([
'status' => true,
'message' => 'User Created',
'data' => $validated
], 200);
return Response::json([$validated], 200);
}
}
output
POST http://127.0.0.1:8000/api/auth/register
HTTP/1.1 200 OK
Host: 127.0.0.1:8000
Date: Sun, 06 Feb 2022 00:09:51 GMT
Connection: close
X-Powered-By: PHP/8.0.13
Cache-Control: no-cache, private
Date: Sun, 06 Feb 2022 00:09:51 GMT
Content-Type: application/json
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 58
Access-Control-Allow-Origin: *
{
"status": true,
"message": "User Created",
"data": {
"name": "Amrith",
"email": "[email protected]",
"password": "abc123"
}
}
Response code: 200 (OK); Time: 581ms; Content length: 110 bytes
Return the User instance (array/JSON representation):
return Response::json([
'status' => true,
'message' => 'User Created',
'data' => $user->toArray()
], 200);
The advantage is (i) it will respect hidden fields on the User instance (ii) any accessors you define on the User model are also respected (iii) it actually represents the User instance rather than the Request payload.
Please or to participate in this conversation.