I want to validate if the field I'm sending to the request is a valid JSON in Laravel (v9.x).
In the next example I just send { "test" : {} } as request content - dd($request):
^ Illuminate\Http\Request {#42 ▼
+attributes: Symfony\Component\HttpFoundation\ParameterBag {#44 ▶}
+request: Symfony\Component\HttpFoundation\ParameterBag {#34 ▶}
+query: Symfony\Component\HttpFoundation\InputBag {#50 ▶}
+server: Symfony\Component\HttpFoundation\ServerBag {#46 ▶}
+files: Symfony\Component\HttpFoundation\FileBag {#47 ▶}
+cookies: Symfony\Component\HttpFoundation\InputBag {#45 ▶}
+headers: Symfony\Component\HttpFoundation\HeaderBag {#48 ▶}
#content: "{"test":{}}"
#languages: null
#charsets: null
#encodings: null
#acceptableContentTypes: null
#pathInfo: "/test"
#requestUri: "/test"
#baseUrl: ""
#basePath: null
#method: "POST"
#format: null
#session: Illuminate\Session\Store {#330 ▶}
#locale: null
#defaultLocale: "en"
-preferredFormat: null
-isHostValid: true
-isForwardedValid: true
#json: Symfony\Component\HttpFoundation\ParameterBag {#34 ▶}
#convertedFiles: []
#userResolver: Closure($guard = null) {#291 ▶}
#routeResolver: Closure() {#300 ▶}
basePath: ""
format: "html"
}
But dd($request->get('test')); outputs:
^ []
Validation I'm doing:
$validator = Validator::make($request->all(), [
'test' => ['present', 'json']
]);
Validation error I get doing dd($validator->errors()):
^ Illuminate\Support\MessageBag {#361 ▼
#messages: array:1 [▼
"test" => array:1 [▼
0 => "The test must be a valid JSON string."
]
]
#format: ":message"
}
Shouldn't be a valid JSON? Shouldn't it have been succeeded the validation?