Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Dhruv Sompura's avatar

Validation is not working in api.

Validation is not working in api. Data ={} Code = $validator = \Validator::make($r->json()->all(), [ 'code' => 'required', 'mobile' => 'required', ]);

But no error messages in response.

0 likes
9 replies
Nakov's avatar

and how does your request body looks like?

{"code": "", "mobile": ""}

??

Nakov's avatar

@Dhruv Sompura since you are using the Validator::make syntax, do you actually return the errors ? Because that one does not handles them automatically:

$validator = \Validator::make($r->json()->all(), [ 'code' => 'required', 'mobile' => 'required', ]);

if ($validator->fails()) 
{
    return response()
        ->withErrors($validator);
}

https://laravel.com/docs/9.x/validation#manually-creating-validators

or for automatic redirection use :

\Validator::make($r->json()->all(), [ 'code' => 'required', 'mobile' => 'required', ])->validate();
Nakov's avatar

@Dhruv Sompura use this :

\Validator::make($r->json()->all(), [ 'code' => 'required', 'mobile' => 'required', ])->validate();
Nakov's avatar

@Dhruv Sompura Does it work? There is a "Best Answer" button you can select on my answer that worked if so :)

anilkumarthakur60's avatar
public function store(Request $request){

$data=$this->validate($request,[
 'code' => 'required', 
'mobile' => 'required',
])
dd($data);
}
Snapey's avatar

If you send in the header Accept: application/json with your request then errors should be returned as json rather than being written to session.

Please or to participate in this conversation.