When trying to submit a POST
request using Axios in Vue to a Laravel API, the validation is running perfect but at the time checking if the validation fails ($data->fails()
) then it is returning a JSON response as an error with status 422. It is not going in the next line where a custom return message is written.
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class AuthController extends Controller
{
//for making register
public function register(Request $request){
// Validator
$data = $request->validate([
'name' => 'required | string',
'email' => 'required | email | unique:users',
'password' => 'required | min:6 | max:10',
'cPassword' => 'required | same:password'
]);
// checking validation
if($data->fails()){
return response()->json(['error'=>$data->errors()->all()], 400);
}
}
}
CodePudding user response:
The error is because you're trying to call a method on an array.
The response type of $request->validate()
is an array
not an instance of a Validator
object. So $data
is an array
and therefore doesn't have a fails()
- or any other - method. The default behaviour for Laravel when using $request->validate()
when validation fails is to automatically throw an exception that redirects back to the client (in this case your Vue app). Alternatively, if validation is successful it populates and returns an array containing the data that passed validation.
Remove the following code block:
if($data->fails()){
return response()->json(['error'=>$data->errors()->all()], 400);
}