I'm currently trying out on how to build a RESTful API with Laravel and I'm currently in the process of creating a new user. This is just a test and I'm getting some result when trying to validate the request using validation in Laravel; here is the result:
I've been trying to create a new one by this code:
public function store() { $validation = Validator::make(Request::all(),[ 'username' => 'required|unique:users, username', 'password' => 'required', ]); if($validation->fails()){ } else{ $createUser = User::create([ 'username' => Request::get('username'), 'password' => Hash::make(Request::get('password')) ]); } }
but then I don't know how to return the error in validation. But it keeps on giving me that HTML as showed in the image when I was trying to do the if with validation->fails()
. Is there a way to get the validation in JSON format?
Validation is the most important aspect while designing an application. It validates the incoming data. By default, base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP requests with a variety of powerful validation rules.
these code will help you, working for me.
$response = array('response' => '', 'success'=>false); $validator = Validator::make($request->all(), $rules); if ($validator->fails()) { $response['response'] = $validator->messages(); } else { //process the request } return $response;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With