Puneet Sharma
Puneet Sharma

Reputation: 103

Validation Error Handing Laravel Sanctum Api in JSON

Laravel usually use following for request validation.

 $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users', 'required_without_all:phone'],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            'phone' => ['required', 'string', 'max:13', 'unique:users', 'required_without_all:email'],
        ]);

This method only add $error variable that can be access using blade files as it render on server only. But now i am using as api Sanctum that which it just show 404. My guess it just redirect back to request and $error is session which can can access with PHP only.

there is work around for it

$validator = Validator::make($request->all(), [
                'name' => ['required', 'string', 'max:255'],
                'email' => ['string', 'email', 'max:255', 'unique:users', 'required_without_all:phone'],
                'password' => ['required', 'confirmed', Rules\Password::defaults()],
                'phone' => ['string', 'max:13', 'unique:users', 'required_without_all:email'],
    ]);
    if ($validator->fails()) {
        return response()->json($validator->errors());
    }

That is just adding extra line i don't want that using this line every time. Can somebody help me for edit validate function which just return any $error as json only.

Clarified Answer

I am self certified noob let me make it like my brain can understand using fetch

let y = await fetch("http://127.0.0.1:8000/api/register", {
  method: "POST", // or 'PUT'
  headers: {
    "Accept" : "application/json",
    "Content-Type": "application/json",
  },
  body: JSON.stringify(x),
}).then(response => response.json());
console.log(y);

I am thinking it a wrong way as there is {"Accept":application/json", "Content-Type": "application/json",} and Accept is important nothing needed to do in back-end.

Upvotes: 0

Views: 1754

Answers (1)

Mostafa Bahri
Mostafa Bahri

Reputation: 2644

You don't need to handle this yourself.

Just make sure your request sends the right header: Accept: application/json

This helps Laravel to know that you want a json response instead of a redirect (that caused the 404).

Sample snippet

Upvotes: 5

Related Questions