Reputation: 3857
I'm using Laravel 5.3 and https://github.com/1000hz/bootstrap-validator
I am checking the users' email against my Database in Laravel to check if the Email is in use or not.
The docs on Bootstrap Validator states to return a 200 if the Email address is fine (i.e doesn't exist) and return a 4xx error if it does.
In my Laravel function, I am doing the following :
public function check_email(Request $request)
{
// Email Address
$email = User::where('email', $request->input('email'))
->take(1)
->get();
$email = $email->toArray();
if(empty($email))
{
return response()->json(['Email Not Taken'], 200);
}
else
{
return response()->json(['Email In Use'], 400);
}
}
Now when I run the validator, It's not showing the message. Is this because Laravel is stricter on its response codes? Or am I just doing something wrong?
My HTML code is as follows :
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" placeholder="Email" data-remote="/validate-email" data-error="Please enter your Email Address" required="required">
@if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span><!-- /.help-block -->
@endif
<span class="glyphicon form-control-feedback" aria-hidden="true"></span>
<div class="help-block with-errors"></div>
</div><!-- /.form-group -->
How do I go about setting a 4xx response with a message in Larvel 5.3?
Thanks
Upvotes: 3
Views: 497
Reputation: 12358
Firstly, don't check if the user exists via a query use Laravel's validator class https://laravel.com/docs/5.3/validation it has already done this work for you, see: https://laravel.com/docs/5.3/validation#rule-unique
Secondly, check out this library which is pretty much doing what you need already: https://github.com/proengsoft/laravel-jsvalidation
Upvotes: 3
Reputation: 1204
You have to validate, either in your controller or create a request class
public function check_email(Request $request)
{
//validate
$this->validate($request, [
'email' => 'required|unique:users',
]);
// Email Address
$email = User::where('email', $request->input('email'))
->take(1)
->get();
}
Upvotes: 4