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'
],
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){
$this->validate($request, [
'username' => 'required|string|unique:users',
'password' => 'required|string|min:8',
'first_name' => 'required|string',
'last_name' => 'required|string',
'email' => 'required|email|unique:users',
]);
try {
$user = new User;
$user->username= $request->input('username');
$user->password =Hash::make($request->input('password'));
$user->first_name = $request->input('first_name');
$user->last_name = $request->input('last_name');
$user->email = $request->input('email');
$user->save();
} catch (Exception $e) {
return response()->json(['error' => 'Registration Failed'], 403);
}
}
This is the typical response get:
"message": "The given data was invalid.",
"status_code": 500
This doesn’t tell anything about the exact validation rule that failed.
How can I solve this?
public function SaveContext(Request $request): JsonResponse
{
try{
$rule = array(
'userName' => 'required|string|max:4',
'password' => 'required |string|max:4'
);
$messages = array(
'userName.required' => 'User name is required.',
'userName.max' => 'User name must not be less than 4 characters.',
'password.required' => 'password is required.',
'password.max' => 'password must not be less than 4 characters.',
);
$this->validate($request, $rule, $messages );
return response()->json(
AppResponse::Success($this->context->SaveContext((object)$request->all()))
);
}catch(\Illuminate\Validation\ValidationException $ex){
return response()->json(
AppResponse::Error($ex->errors())
);
}
}
You can do something like this:
try {
$this->validate($request, [
'username' => 'required|string|unique:users',
'password' => 'required|string|min:8',
'first_name' => 'required|string',
'last_name' => 'required|string',
'email' => 'required|email|unique:users',
]);
}
catch (\Illuminate\Validation\ValidationException $ex ) {
$errors = $ex->errors();
return response()->json($errors, 422);
}
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');
}
}
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?