Unique validation is not working in Laravel
$validator = Validator::make(request()->all(),
[
'firstname'=> 'required',
'lastname'=>'required',
'email'=>"required|unique:users,email",
'password'=>'required',
'phone'=>"required|unique:users,phone"
]);
if ($validator->fails()){
return Response::json(
array(
'code' => 400,
'message' => $validator->messages()->toArray()
), 400);
}
not working for non unique values
Try this
$validator = Validator::make(request()->all(),
[
'firstname'=> 'required',
'lastname'=>'required',
'email'=>'required|unique:users',
'password'=>'required',
'phone'=>'required|unique:users'
]);
if ($validator->fails()) {
return $validator->errors();
}
}
PLease TRy this
use Illuminate\Support\Facades\Validator;
protected function validator(array $data)
{
return Validator::make($data, [
'fairstname' => ['required'],
'lastname' => ['required'],
'email' => ['required','email','unique:users'],
'phone_number'=>['required','unique:users'],
'password' => ['required'],
]);
}
public function register(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
return redirect()->route('register')->withErrors($validator, 'register');
}
}
Related
I can save the data to the database just fine. And then I right after the creation I'll login that current user with the email. But it will always be sending a request. What might be the problem here?
class RegisterController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/home';
private $loginProxy;
public function __construct(LoginProxy $loginProxy)
{
$this->loginProxy = $loginProxy;
$this->middleware('guest')->except('logout');
}
function apiRegisterUser(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json(array('code' => 406, 'error' => $validator->messages()), 406);
} else {
// Log::channel('abuse')->info('user');
$user = User::create(['name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password']),
'referral_code' => str_random(10)
]);
$user->updateLastRoute(1);
$credentials = $this->loginProxy->attemptLogin($request['email'], $request['password']);
return response()->json($this->successResponse(200, "Login successfull", $credentials), 200);
}
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
use auth()->attempt() function i m not sure about loginProxy
but auth()->attempt() this should work
$credentials = [
"email" => $request['email'],
"password" => $request['password']
];
if (auth()->attempt($credentials)) {
return response()->json($this->successResponse(200, "Login successfull", $credentials), 200);
}
public function register(Request $request){
$validator = \Validator::make($request->all(), [
'first_name' => 'required|min:3',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required',
'address' => 'required',
'phone_number' => 'required',
]);
if($request->user_type == 1 ){
$validator = \Validator::make($request->all(), [
'dob' => 'required'
]);
}
if($request->user_type == 2 ){
$validator = \Validator::make($request->all(), [
'doctor_practice' => 'required'
]);
}
// then, if it fails, return the error messages in JSON format
if ($validator->fails()) {
return response()->json($validator->messages(), 401);
}
How can I set the validator based on user type? I did try does not work fine.
Add rules array by users type and put rules at last
$rules = [
'first_name' => 'required|min:3',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required',
'address' => 'required',
'phone_number' => 'required',
];
if($request->user_type == 1 ){
$rules['dob'] = 'required';
}else if($request->user_type == 2 ){
$rules['doctor_practice'] = 'required';
}
$validator = \Validator::make($request->all(), $rules);
if ($validator->fails()) {
return response()->json($validator->messages(), 401);
}
It is better and more correctly to use embedded mechanism of validation.
$rules = [
'first_name' => 'required|min:3',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required',
'address' => 'required',
'phone_number' => 'required',
'dob' => 'required_if:user_type,1',
'doctor_practice' => 'required_if:user_type,2',
];
$validator = \Validator::make($request->all(), $rules);
if ($validator->fails()) {
return response()->json($validator->messages(), 401);
}
It is described in Laravel documentation
required_if:anotherfield,value,...
The field under validation must be present and not empty if the anotherfield field is equal to any value.
I'm trying to make email optional when user signs up. Here is package. So I removed email' => 'required|email|unique:users', in this function:
public function signup(Request $request)
{
$credentials = $request->all();
$validator = Validator::make($credentials, [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required|min:3'
]);
if ($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
try {
$user = $this->users->create($request->except('roles', 'permissions'));
if (!$user->id) {
return $this->response->error('could_not_create_user', 500);
}
$hasToReleaseToken = Config::get('boilerplate.signup_token_release');
if ($hasToReleaseToken) {
return $this->login($request);
}
return $this->response->created();
} catch (\Exception $e) {
return $this->response->error($e->getMessage(), 500);
}
}
then in config-boilerplate.php I also removed email:
'signup_fields_rules' => [
'name' => 'required',
'email' => 'required|email|unique:users',///// this
'password' => 'required|min:6'
],
But when I sign up I get this error :
"message": "Undefined index: email",
"status_code": 500,
"debug": {
"line": 173,
"file": "/Users/MyMac/Desktop/Project/laravel-5.3-boilerplate-api-jwt-vue2/vendor/dingo/api/src/Http/Response/Factory.php",
"class": "Symfony\Component\HttpKernel\Exception\HttpException",
the route:
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->post('auth/signup', 'App\Api\V1\Controllers\AuthController#signup');
Is there anything I need to disable to allow users sign-up with or without email ?
If you want to make email as optional field, just use sometimes|email See Docs. Try below code:
public function signup(Request $request)
{
$credentials = $request->all();
$validator = Validator::make($credentials, [
'name' => 'required',
'email' => 'sometimes|email',
'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required|min:3'
]);
if ($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
try {
$user = $this->users->create($request->except('roles', 'permissions'));
if (!$user->id) {
return $this->response->error('could_not_create_user', 500);
}
$hasToReleaseToken = Config::get('boilerplate.signup_token_release');
if ($hasToReleaseToken) {
return $this->login($request);
}
return $this->response->created();
} catch (\Exception $e) {
return $this->response->error($e->getMessage(), 500);
}
}
config-boilerplate.php
'signup_fields_rules' => [
'name' => 'required',
'email' => 'sometimes|email',///// this
'password' => 'required|min:6'
],
I do have a feeling that I need to use Auth:: or something here to link to passes. Am I correct
Issue Line
if($validator->passes())
`
getLoginCredentials
protected function getLoginCredentials(Request $request)
{
$validator = $this->loginValidation($request);
if($validator->passes())
{
return[
'email' => Request::input('email'),
'password' => Request::input('password'),
'type' => 1
];
}else{
return redirect()->back()->withErrors();
}
}
loginValidation
protected function loginValidation($request)
{
$rules = array(
'email' => 'required|email',
'password' => 'required',
);
$this->validate( $request , $rules);
}
I think the actual problem is in the loginValidation method that should return an object. Please, see my code below. I've also changed getLoginCredentials a bit as Request shouldn't be called statically.
protected function getLoginCredentials(Request $request)
{
$validator = $this->loginValidation($request);
if ($validator->passes()) {
return [
'email' => $request->input('email'),
'password' => $request->input('password'),
'type' => 1
];
} else {
return redirect()->back()->withErrors();
}
}
loginValidation
protected function loginValidation(Request $request)
{
$rules = [
'email' => 'required|email',
'password' => 'required',
];
return Validator::make($request->all(), $rules);
}
I'm trying to get my registration page to show, the controller logic seems ok but I keep getting this:
BadMethodCallException
Method [ register] does not exist.
here is my controller logic:
<?php
class UserController extends BaseController {
public function register()
{
if(Sentry::check()){
return Redirect::to('myaccount');
}
return View::make("user.register")->with("title", "Avenue - Register")->with("page_title", "Register");
}
public function postRegister()
{
$rules = array(
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|confirmed',
'password_confirmation' => 'required'
);
$input = Input::get();
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::to('register')->with_input()->with_errors($validation);
}
$user = Sentry::createUser(array(
'first_name' => Input::get('first_name'),
'last_name' => Input::get('last_name'),
'email' => Input::get('email'),
'password' => Input::get('password'),
'metadata' => array(
'phone' => Input::get('phone'),
'date-of-birth' => Input::get('date-of-birth'),
'nationality' => Input::get('nationality'),
'gender' => Input::get('gender'),
'category' => Input::get('category'),
),
));
Mail::send('emails.welcome', $data, function($message)
{
$message->to(Input::get('email'))->subject('Welcome to Avenue254!');
});
}
public function getLogin()
{
if(Sentry::check()){
return Redirect::to('myaccount');
}
return View::make("user.login")->with("title","Avenue254 - Login")->with("page_title","Login");
}
public function postLogin()
{
$rules = array(
'email' => 'required|email',
'password' => 'required',
);
$input = Input::get();
$validation = Validator::make($input, $rules);
if ($validation->fails())
{
return Redirect::to_route('login')->with_errors($validation->errors)->with_input();
}
$credentials = array( 'email'=> Input::get('email'), 'password'=>Input::get('password') );
if (Sentry::authenticate($credentials, false))
{
return Redirect::to('myaccount');
}
else
{
return Redirect::to('login')->with("error", "There is problem with login please try again");
}
}
public function getMyaccount()
{
if(!Sentry::check()){
return Redirect::to('login')->with("error", "Please login to access your account");
}
$user = Sentry::getUser();
return View::make("users.myaccount")->with("title","Avenue254" - "My Account")->with("page_title","My Account")->with('user',$user);
}
public function postProfile()
{
$user = Sentry::getUser();
$rules = array(
'email' => 'required|email|unique:users,email,'.$user['id'],
);
$input = Input::get();
$validation = Validator::make($input, $rules);
if ($validation->fails()) {
return Redirect::to('myaccount')->with_input()->with_errors($validation);
}
$user_data = array(
'email' => Input::get('email'),
'metadata' => array(
'first_name' => Input::get('first_name'),
'last_name' => Input::get('last_name'),
'phone' => Input::get('phone'),
'date-of-birth' => Input::get('date-of-birth'),
),
);
if ($user->update($user_data))
{
return Redirect::to('myaccount')->with('success', 'Your information has been updated successfully.');
}
else
{
return Redirect::to('myaccount')->with('error', 'Something went wrong!.');
}
}
}
and my routes:
Route::get('register', array('as' => 'getregister', 'uses' => 'UserController#
register'));
Route::get('myaccount', array('as' => 'myaccount', 'uses' => 'UserController#
myaccount'));
Route::post('register', array('as' => 'postregister', 'uses' =>
'UserController#postRegister'));
Whenever I try to route to register I get this error, I have tried everything unsuccessfully. What could I be doing wrong?