I'm working with Laravel and this is my RegisterController Class based on API:
class RegisterController extends AuthController
{
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string',
'email' => 'required|email|unique:users',
'password' => 'required|string|min:6|max:13|same:password_confirmation',
]);
$errors = [];
if ($validator->fails()) {
foreach($validator->errors()->all() as $err){
array_push($errors, $err);
}
return view('auth.index', compact('errors'));
}else{
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => bcrypt($request->password),
]);
Auth::login($user);
$token = $user->createToken('API Token')->accessToken;
return response()->json(['token' => $token], 201);
}
}
}
It works fine but as you see I tried showing validation errors by returning the view and compacted the errors array to it:
return view('auth.index', compact('errors'));
This is wrong, however, I don't know how to capture the response json for the error showing.
So if you know how to do this, please let me know.
Thanks in advance.
->validateinstead ofmake... read the documentation...