I have a function in my laravel controller for login to a website, and I'm having trouble figuring out the best way to pass the two fields (email, and password)
into a function call loginAttempt()
Currently I have:
public function login(Request $request)
{
//getting email and password form fields for validation
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
//Need to pass email and password into the loginAttempt() function
$authService = new AuthService();
$login = $authService->loginAttempt();
dd($login);
}
I know I can use $login = $authService->loginAttempt($arguments); but the function I'm passing into needs the email and password as separate variables.
How can I pass them both into that loginAttempt() function call?
Just grab the values from the input using $request->input as shown below
public function login(Request $request)
{
//getting email and password form fields for validation
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
//Need to pass email and password into the loginAttempt() function
$email = $request->input ('email');
$password = $request->input ('password');
$authService = new AuthService();
$login = $authService->loginAttempt($email, $password);
dd($login);
}
you can mulitple variable two ways function to function
first way
passing each variable as separated
$authService = new AuthService();
$login = $authService->loginAttempt($request->email, $request->password);
second way
create a single dimension array used like that
$authService = new AuthService();
$login = $authService->loginAttempt(['email' => $request->email, 'password' => $request->password]);
and in your AuthService getting value by using key like that
$data['email'] or $data['password']
Related
how to make correct validation if i have input from where i can sign in with username or email, i want to if user will text username in field, it check if this username doesnt exist, then fail, also if he will choose to use email to sign in, then it will check if email doesnt exist then fail. (login form have only 2 inputs, login and password, in login u can text username or email)
my rule =
public function rules()
{
return [
'user' => 'required|min:3|exists:users,username,email]',
'password' => 'required',
];
}
You can use custom login as :
public function login(Request $request)
{
$request->validate([
'user' => 'required|min:3]',
'password' => 'required',
]);
}
$userName_or_Email = $request->user;
$password = $request->password;
$user = User::where('username',$userName_or_Email)->first();
if(empty($user)){
$user = User::where('email',$userName_or_Email)->first();
}
if(empty($user)){
return new Response()->with('error','Username or email not available in database');
}
if(Hash::check($password, $user->password)){
// Login successful code
}else{
return new Response()->with('error','Username or email not available in database');
}
While changing the password I am using this function
public function passwordChange(Request $request, $userId)
{
$user = User::find($userId);
$user->password = Crypt::encrypt(Input::get('password'));
$user->save();
return redirect('my-profile');
}
So in my mongoDb database password insert in encrypted form, So whenever I have to login in system at that time how can I compare my password with password of database
public function authenticate(Request $request)
{
$rules = array(
'company_email' => 'required|email|exists:users,company_email',
'password' => 'required|string|max:20|min:4',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return view('pages.login')->with('v_errors', $validator->errors()->messages());
}
else
{
//get email and query
$authenticateMe = $request->only('company_email', 'password');
$user = User::where($authenticateMe)->first();
if (empty($user))
{
return view('pages.login')->with('not_exists', 'true');
}
//session set
// Session::put('key', $user->username, $user->file);
Session::put('key', ['username' => $user->username, 'email' => $user->company_email, 'userId' => $user->id, 'profilePicture' => $user->file]);
return redirect('my-profile');
}
}
I am not using php artisan make:auth
will anyone please help??
Instead of encrypting the password, use hashing. Laravel has its own documentation about how to use that: https://laravel.com/docs/5.8/hashing
Simply you can not decrypt an encrypted password but you can check user credentials by adding an array of user email & password to Auth::attempt() function Here is a link to the description: https://laravel.com/docs/5.8/authentication#authenticating-users?
Here is your function using Auth::attempt():
public function authenticate(Request $request)
{
$rules = array(
'company_email' => 'required|email|exists:users,company_email',
'password' => 'required|string|max:20|min:4',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return view('pages.login')->with('v_errors', $validator->errors()->messages());
}
else
{
//get email and query
$authenticateMe = $request->only('company_email', 'password');
if (Auth::attempt($authenticateMe)) {
$user = User::find(Auth::user()->id);
//session set
// Session::put('key', $user->username, $user->file);
Session::put('key', ['username' => $user->username, 'email' => $user->company_email, 'userId' => $user->id, 'profilePicture' => $user->file]);
return redirect('my-profile');
}else{
return view('pages.login')->with('not_exists', 'true');
}
}
}
And do not forget to add use Auth; to the function controller
I have this error in Laravel latest for authentication
Argument 2 passed to Illuminate\Auth\SessionGuard::__construct() must
be an instance of Illuminate\Contracts\Auth\UserProvider, null given,
called in
G:\xampp\htdocs\newrestaurantcrm\vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php
can anyone give me an idea about this error why this error is occurring?
I am using below code for authentication in my Auth\AuthController.php file
protected function login(Request $request) {
$email = $request->email;
$password = bcrypt($request->password);
if (Auth::login(['email' => $email, 'password' => $password])) {
return redirect()->intended('/admin/dashboard');
}
}
Change your code to
public function login(Request $request) {
$email = $request->get('email');
$password = $request->get('password');
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return redirect()->intended('/admin/dashboard');
}
}
I changed the protected to public, Auth::login() to Auth::attempt(). If you use login, you will actually have to pass the User object you like to login as. You do not need to encrypt the password to pass to attempt and. To make this simpler you can write
public function login(Request $request) {
if (Auth::attempt($request->only('email', 'password'))) {
return redirect()->intended('/admin/dashboard');
}
}
This of course assumes that your form has correct name for fields, email and password and also has same field email and password in users table as well.
When you are authenticate user against email and password then use Auth::attempt or Auth::once (For single request). When we have user instance and we want to login with that user instance then we use Auth::login. For your case use Auth::attempt like this
public function login(Request $request) {
$email = $request->email;
$password = bcrypt($request->password);
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return redirect()->intended('/admin/dashboard');
}
}
Details: https://laravel.com/docs/5.6/authentication#included-authenticating
Hello Everyone
My question is how can we authenticate our email and password in laravel 5.3 ?
I am not using Auth here , I am trying to create login system manually
This is user register method
public function post_register(Request $request){
$this->validate($request , [
'username' => 'required|' ,
'email' => 'required|email|unique:registers' ,
'password' => 'required|min:6',
'cp' => 'required|same:password']);
$data = new Register;
$data->username = $request->username;
$data->email = $request->email;
$data->password = bcrypt($request->password);
$data->save();
return Redirect::back()->with('success' , 'user registred');
}
This is login method
public function post_login(Request $request){
$this->validate($request , [
'email' => 'required|email' ,
'password' => 'required']);
$data = Register::where('email' , $request->email)->exists();
if($data){
Session::put('email' , $request->email);
return Redirect::to('profile');
}
else{
return Redirect::to('login');
}
this code is working , but problem is that if i enter registered email and unregistered password then it redirect to profile page.
i am not able to authenticate user with email and password because i am using bcrypt() hash function in password and when i try to match http request with stored password , it show error
Please help me ,Thanks
It wont work because you are comparing the string results of the hash which isnt correct.
Changes you Register Function
$data->password = Hash::make($request->password);
Change Your Login function
public function post_login(Request $request){
$this->validate($request , [
'email' => 'required|email' ,
'password' => 'required']);
$data = Register::where('email' , $request->email)->first();
if($data){
if(Hash::check($request->password, $data->password)){
Session::put('email' , $request->email);
return Redirect::to('profile');
}
}
return Redirect::to('login');
}
Explanation
These changes allow you to use Laravel's built in Hashing functionality for Generating Hashes At Registration & Calculating if a hash is valid during login.
Change your code to this.
$data = Register::where('email' , $request->email)
->where('password' ,bcrypt($request->password))
->exists();
In laravel, when a new user is registering to my site and the email they use already exist in the database. how can tell the user that the email already exist ?. I am new to laravel framework. A sample code would be nice too.
The validation feature built into Laravel lets you check lots of things, including if a value already exists in the database. Here's an overly simplified version of what you need. In reality you'd probably want to redirect back to the view with the form and show some error messages.
// Get the value from the form
$input['email'] = Input::get('email');
// Must not already exist in the `email` column of `users` table
$rules = array('email' => 'unique:users,email');
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
echo 'That email address is already registered. You sure you don\'t have an account?';
}
else {
// Register the new user or whatever.
}
);
Laravel has built-in human readable error messages for all its validation. You can get an array of the these messages via: $validator->messages();
You can learn more about validation and what all you can do with it in the Laravel Docs.
Basic Usage Of Unique Rule
'email' => 'unique:users'
Specifying A Custom Column Name
'email' => 'unique:users,email_address'
Forcing A Unique Rule To Ignore A Given ID
'email' => 'unique:users,email_address,10'
Adding Additional Where Clauses
You may also specify more conditions that will be added as "where" clauses to the query:
'email' => 'unique:users,email_address,NULL,id,account_id,1'
The above is from the documentation of Laravel
You could add:
public static $rules = [
'email' => 'unique:users,email'
];
You can add more rules to the $rules like:
public static $rules = [
'email' => 'required|unique:users,email'
];
It will automatically produce the error messages
and add:
public static function isValid($data)
{
$validation = Validator::make($data, static::$rules);
if ($validation->passes())
{
return true;
}
static::$errors = $validation->messages();
return false;
}
to the model User.php
Then in the function you're using to register, you could add:
if ( ! User::isValid(Input::all()))
{
return Redirect::back()->withInput()->withErrors(User::$errors);
}
if(sizeof(Users::where('email','=',Input::get('email'))->get()) > 0) return 'Error : User email exists';
The great resource is only Laravel Documentation #
enter link description here
I also did like below when integrating user management system
$user = Input::get('username');
$email = Input::get('email');
$validator = Validator::make(
array(
'username' => $user,
'email' => $email
),
array(
'username' => 'required',
'email' => 'required|email|unique:users'
)
);
if ($validator->fails())
{
// The given data did not pass validation
echo 'invalid credentials;';
// we can also return same page and then displaying in Bootstap Warning Well
}
else {
// Register the new user or whatever.
$user = new User;
$user->email = Input::get('email');
$user->username = Input::get('username');
$user->password = Hash::make(Input::get('password'));
$user->save();
$theEmail = Input::get('email');
// passing data to thanks view
return View::make('thanks')->With('displayEmail', $theEmail);
}
public function userSignup(Request $request, User $data){
# check user if match with database user
$users = User::where('email', $request->email)->get();
# check if email is more than 1
if(sizeof($users) > 0){
# tell user not to duplicate same email
$msg = 'This user already signed up !';
Session::flash('userExistError', $msg);
return back();
}
// create new files
$data = new User;
$data->name = $request->name;
$data->email = $request->email;
$data->password = md5($request->password);
$data->save();
//return back
Session::flash('status', 'Thanks, you have successfully signup');
Session::flash('name', $request->name);
# after every logic redirect back
return back();
}
I think when u try something like this you earn a smooth check using Model
We can use the Validator.
In your Controller.
$validator = $request->validate([
'name' => 'required',
'phone' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required',
]);
In View
#error('email') <span class="text-danger error">{{ $message }}</span>#enderror
$this->validate($request, [
'fname' => 'required',
'lname' => 'required',
'email' => 'required|min:4|email|unique:users',
'password' => 'required',
]);
Try This