Reset password in Laravel by typing email manually - php

How can I make this reset password work without using a token and adding an email manually to reset password.
Like for example in the image I want to change the password to the email I added which is edgar.lozoya#ujed.mx
How can I make this reset password work without using a token and adding an email manually to reset password.
Like for example in the image I want to change the password to the email I added which is edgar.lozoya#ujed.mx
This is the reset.blade.php:
`#extends('layout.layout_reset')
#section('content')
<section class=" container section">
<h1 class="h2 text-center">
Restablecer contraseña
</h1>
#alert(['class' => 'alert--has-icon size-caption'])
#endalert
<div class="login-form ">
<base-form action="{{ url('contrasena/restablecer') }}"
inline-template
v-cloak
>
<form method="POST" class="form-boxed" action="{{ route('password.update') }}" >
#csrf
<text-field name="token" type="hidden" v-model="fields.token" maxlength="60" placeholder="" ></text-field>
<div class="form-control">
<label for="email">Correo electrónico</label>
<text-field name="email" type="email" v-model="fields.email" maxlength="60" value="{{ $email ?? old('email') }}" placeholder="" initial=""></text-field>
<field-errors name="email"></field-errors>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{$message}}</strong>
</span>
#enderror
</div>
<div class="form-control">
<label for="password">Nueva contraseña</label>
<text-field name="password" type="password" v-model="fields.password" maxlength="60" placeholder="" initial=""></text-field>
<field-errors name="password"></field-errors>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{$message}}</strong>
</span>
#enderror
</div>
<div class="form-control">
<label for="password_confirmation">Confirmar nueva contraseña</label>
<text-field name="password_confirmation" type="password" v-model="fields.password_confirmation" maxlength="60" placeholder="" initial=""></text-field>
<field-errors name="password_confirmation"></field-errors>
#error('password_confirmation')
<span class="invalid-feedback" role="alert">
<strong>{{$message}}</strong>
</span>
#enderror
</div>
<div class="text-center">
<form-button type="submit" class="btn--success w-full">
Enviar
</form-button>
</div>
</form>
</base-form>
<br>
<br>
<br>
<br>
</div>
</section>
#endsection
`
This is the reset password controller code:
`<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
use App\User:
class ResetPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Where to redirect users after resetting their password.
*
* #var string
*/
protected $redirectTo = 'admin';
protected function redirectTo(){
if( Auth()->user()->role == 1){
return route('admin.dashboard');
}
elseif( Auth()->user()->role == 2){
return route('admin.dashboard');
}
}
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
public function showResetForm(Request $request, $token = null)
{
return view('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
}
these are the routes in the web.php fileRoute::post('passwords/reset', 'Auth\ResetPasswordController#reset')->name('password.update');
Route::post('auth/email', 'Auth\ForgotPasswordController#sendResetLinkEmail')->name('password.email'); `
I tried eliminating the token variables and requesting the email in the reset password controller

Related

Can't login using Laravel with correct credentials

Good day, I've been having a hard time solving this problem for almost a week now. I'm trying to login my Laravel project, the problem is it doesn't login even though the email and password (hashed in db) input is correct. Any help will be greatly appreciated. Below are the code of my files for LoginController.php, login.blade.php, and web.php
LoginController.php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Auth;
use DB;
use App\Models\Distributor;
use Carbon\Carbon;
use Session;
use Brian2694\Toastr\Facades\Toastr;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except([
'logout',
'locked',
'unlock'
]);
}
public function login()
{
return view('auth.login');
}
public function username(){ return 'email_address';
}
public function authenticate(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
]);
$email = $request->email;
$password = $request->password;
if (Auth::attempt(['emailAddress'=>$email,'password'=>$password,])) {
Toastr::success('Login successfully :)','Success');
return redirect()->intended('orders.sellload');
}elseif (Auth::attempt(['emailAddress'=>$email,'password'=>$password])) {
Toastr::success('Login successfully :)','Success');
return redirect()->intended('orders.sellload');
}elseif (Auth::attempt(['emailAddress'=>$email,'password'=>$password,])) {
Toastr::success('Login successfully :)','Success');
return redirect()->intended('admin.distributor');
}
elseif (Auth::attempt(['emailAddress'=>$email,'password'=>$password])) {
Toastr::success('Login successfully :)','Success');
return redirect()->intended('admin.distributor');
}else{
Toastr::error('fail, WRONG USERNAME OR PASSWORD :)','Error');
return redirect('login');
}
}
public function logout()
{
Auth::logout();
Toastr::success('Logout successfully :)','Success');
return redirect('login');
}
}
login.blade.php
#extends('layouts.app')
#section('content')
<div id="auth">
<div class="row h-100">
<div class="col-lg-3 col-12">
</div>
<div class="col-lg-6 col-12">
<div id="auth-left">
<p style="text-align:center;"><img src="assets/images/logo/icon.png" width="300" align>
</p>
{{-- message --}}
{!! Toastr::message() !!}
<p style="text-align:center;">Welcome to John Doe Portal</p>
#if(session()->has('error'))
<div class="text-danger text-center text-bold">
{{ session()->get('error') }}
</div>
#endif
<br>
<form method="POST" action="{{ route('login') }}" class="md-float-material">
#csrf
<div class="form-group position-relative has-icon-left mb-4">
<input type="text" class="form-control form-control-lg #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" placeholder="Enter email">
<div class="form-control-icon">
<i class="bi bi-person"></i>
</div>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="form-group position-relative has-icon-left mb-4">
<input type="password" class="form-control form-control-lg #error('password') is-invalid #enderror" name="password" placeholder="Enter Password">
<div class="form-control-icon">
<i class="bi bi-shield-lock"></i>
</div>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="form-check form-check-lg d-flex align-items-end">
<input class="form-check-input me-2" type="checkbox" value="remember_me" id="remember_me" name="remember_me">
<label class="form-check-label text-gray-600" for="flexCheckDefault">
Keep me logged in
</label>
</div>
<button class="btn btn-primary btn-block btn-lg shadow-lg mt-5">LOG IN</button>
</form>
</div>
</div>
<div class="col-lg-3 col-12">
</div>
</div>
</div>
#endsection
web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PhotosController;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Auth\RegisterController;
use App\Http\Controllers\ResetPasswordController;
use App\Http\Controllers\FormController;
use App\Http\Controllers\UserManagementController;
use App\Http\Controllers\LockScreen;
Route::get('/', function () {
return view('auth.login');
});
Route::get('/insert', function () {
$activationCodeParam=123456;
$idParentParam=1;
$tierParam=2;
$store = DB::select('
call createStore(?,?,?)',
array(activationCodeParam,idParentParam,tierParam));
});
Route::group(['middleware'=>'auth'],function()
{
Route::get('user',function()
{
return view('orders.sellload');
});
Route::get('home',function()
{
return view('orders.sellload');
});
});
Auth::routes();
Route::get('home',function()
{
return view('orders.sellload');
});
// ----------------------------- home dashboard ------------------------------//
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
// -----------------------------login----------------------------------------//
Route::get('/login', [App\Http\Controllers\Auth\LoginController::class, 'login'])->name('login');
Route::post('/login', [App\Http\Controllers\Auth\LoginController::class, 'authenticate']);
Route::get('/logout', [App\Http\Controllers\Auth\LoginController::class, 'logout'])->name('logout');
You are missing the session refresh before your redirect.
// validation here
if(Auth::attempt(['emailAddress'=>$email,'password'=>$password,])) {
Toastr::success('Login successfully :)','Success');
$request->session()->regenerate(); // refresh session
return redirect()->intended('orders.sellload');
}
// …
This shouldn’t be related, but also your if-conditions don’t make sense — because they are all the same and if one matches, the other never can be reached.
Have you tried changing
if (Auth::attempt(['emailAddress'=>$email,'password'=>$password,]))
emailAddress
to email?

Register Logs User In, But Login Doesn't Laravel

I am making a web app using Laravel 8, but my Authentication is being a little funky.
I created the Authentication using the php artisan ui:auth command.
Registration works fine: adding the new User to the database, logging in the user, redirecting to the home page.
The issue is that when I now try to login to that same user, the form just refreshes and doesn't log the user in.
Any help is much appreciated. Please let me know if you need more information!
Pertinent Code
web.php:
NOTE:
In PHPStorm, Auth is underlined as "undefined class Auth"
/adminregister is how I'm registering admin accounts for now.
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('home');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/adminregister', function () {
return view('auth/adminregister');
});
Route::get('/getlocations', [App\Http\Controllers\LocationController::class, 'index']);
Route::post('/addlocation', [App\Http\Controllers\LocationController::class, 'store']);
User.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'username',
'password',
'role'
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function locations()
{
return $this->hasMany(Location::class);
}
public function reviews()
{
return $this->hasMany(Review::class);
}
}
LoginController.php:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
login.blade.php:
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Login') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('login') }}">
#csrf
<div class="form-group row">
<label for="username" class="col-md-4 col-form-label text-md-right">Username</label>
<div class="col-md-6">
<input id="username" type="text" class="form-control #error('username') is-invalid #enderror" name="username" value="{{ old('username') }}" required autocomplete="username" autofocus>
#error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="current-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
#if (Route::has('password.request'))
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
#endif
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
RegisterController.php:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'username' => ['required', 'string', 'max:255'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'username' => $data['username'],
'password' => Hash::make($data['password']),
'role' => $data['role']
]);
}
}
register.blade.php
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Register') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('register') }}">
#csrf
<div class="form-group row">
<input name="role" type="hidden" value="0">
<label for="username" class="col-md-4 col-form-label text-md-right">{{ __('Username') }}</label>
<div class="col-md-6">
<input id="username" type="text" class="form-control #error('username') is-invalid #enderror" name="username" value="{{ old('username') }}" required autocomplete="username" autofocus>
#error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
{{-- <div class="form-group row">--}}
{{-- <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>--}}
{{-- <div class="col-md-6">--}}
{{-- <input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email">--}}
{{-- #error('email')--}}
{{-- <span class="invalid-feedback" role="alert">--}}
{{-- <strong>{{ $message }}</strong>--}}
{{-- </span>--}}
{{-- #enderror--}}
{{-- </div>--}}
{{-- </div>--}}
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
User Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('username')->unique();
$table->string('password');
$table->tinyInteger('role');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Things I've Tried
Searched the web, and found a thread which seemed promising, but the solution was for a different version of the Authentication than I used: Laravel 5.2 login doesn't work, no redirect and no errors.
Adding a route that redirects back to home after reaching /login, but this wouldn't log in the user.
Deleting the migrations and re-running them using php artisan migrate:fresh.
A few other things that are slipping my mind now, but all to no avail.
By default, laravel use email for authentication but if you want to login with username (or something else). You need to override the username() method into the LoginController class. You don't need to change things in AuthenticatesUsers because, in my opinion, it's not a good thing to do that.
/**
* Get the login username to be used by the controller.
*
* #return string
*/
public function username()
{
return 'username';
}
Similarly, you can override other methods also, But instead, if you use email for your authentication then you don't need to do that.
I've observed that you're making use of username to login instead of email by default. Perhaps you can try changing the following under AuthenticatesUsers?
FROM
public function username()
{
return 'email';
}
TO
public function username()
{
return 'username';
}

Route that handles registration request return 404

I'm trying to let someone register but when I click the register button I get 404 not found.
I've had this issue before but that was cuz of how the routes were ordered but as you can see I only have 2 in this project and the csrf is also implemented as required...
My form:
<!-- register form -->
<div class="col-md-6">
<h2>Register</h2>
<form method="post" action="{{ route('register') }}">
#csrf
<div class="form-group">
<label for="username">Your username</label>
<input type="text" class="form-control" name="username">
#if ($errors->has('username'))
<br><span class="text-danger">{{ $errors->first('username') }}</span>
#endif
</div>
<div class="form-group">
<label for="email">Your Email</label>
<input type="email" class="form-control" name="email">
#if ($errors->has('email'))
<br><span class="text-danger">{{ $errors->first('email') }}</span>
#endif
</div>
<div class="form-group">
<label for="password">Your password</label>
<input type="password" class="form-control" name="password">
#if ($errors->has('password'))
<br><span class="text-danger">{{ $errors->first('password') }}</span>
#endif
</div>
<div class="form-group">
<label for="repeat-password">Repeat your password</label>
<input type="password" class="form-control" name="repeat-password">
#if ($errors->has('repeat-password'))
<br><span class="text-danger">{{ $errors->first('repeat-password') }}</span>
#endif
</div>
<input type="submit" class="btn btn-primary" value="Register">
</form>
</div>
My web.php file with my routes:
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'PagesController#index')->name('home');
Route::post('/register', 'PagesController#register')->name('register');
This is my controller handling the functions:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\RegistrationRequest;
class PagesController extends Controller
{
public function index() {
return view('pages.home');
}
public function register(RegistrationRequest $request) {
$user = new User;
$user->username = $request->input('username');
$user->email = $request->input('email');
$user->password = $request->bcrypt(input('password'));
$user->save();
session()->flash('status', 'Your account has been created!');
return Redirect::back();
}
}
Lastly the registration request:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegistrationRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|min:3|max:30',
'email' => 'email|unique:users',
'password' => 'required|confirmed|min:6'
];
}
}
So apperantly after installing the ui package all my custom routes stopped working. So starting a new project with the same code except the package works.

unable to override laravel 5.4 default field name in login Authentication

using below given code i want to override laravel default fields and table name with my custom by this code my table name is overridden but field name "email" is not overriding by "userEmail"
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = 'User';
protected $email = 'userEmail';//overriding laravel default field name
public $fillable = [
'name', 'userEmail', 'password',
];
public static $fillable2 = [
'name', 'userEmail', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
when using above code getting following error from laravel
using laravel Authentication Controller
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
You able to override the email field to userEmail the by putting the following in Auth/LoginController.php
public function username()
{
return 'userEmail';
}
When authenticating by custom method , you need to change username to userEmail,
Auth::attempt( array('userEmail' => $username, 'password' => $password) )
In your AuthController add a property named username set to your desired field name.
protected $username = 'userEmail';
This another version of my answer, it will surely works if you have laravel 5.2
Add the following method
public function loginUsername()
{
return 'userEmail';
}
To the
AuthController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
public function loginUsername()
{
return 'userEmail';
}
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users,userEmail',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'userEmail' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
Don't forget to modify the validator and create methods according to the new field name.
Note: need to change login.balde.php and register.balde.php which are came along with laravel5.2
login.balde.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Login</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ url('/login') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('userEmail') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="userEmail" value="{{ old('userEmail') }}">
#if ($errors->has('userEmail'))
<span class="help-block">
<strong>{{ $errors->first('userEmail') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password">
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember"> Remember Me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
<i class="fa fa-btn fa-sign-in"></i> Login
</button>
<a class="btn btn-link" href="{{ url('/password/reset') }}">Forgot Your Password?</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
register.balde.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Register</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ url('/register') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="name" class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}">
#if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}">
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password">
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">
<label for="password-confirm" class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation">
#if ($errors->has('password_confirmation'))
<span class="help-block">
<strong>{{ $errors->first('password_confirmation') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
<i class="fa fa-btn fa-user"></i> Register
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection

Laravel login and register forms on the same page in Laravel 5.2

From default auth and register sistem that comes with Laravel 5.2,
Just made a simple view, that could be the welcome page, and to include the login and register forms.
At the moment, if any button is pressed, the validation checks and finds errors from both forms, and are highlighted all of them which are required.
So what is the best solution to include them and maybe a separate validation for each?
I tried to change the default login sistem to be different from the register form input names, but i think there is a chain, due to validation and adding input values into database.
<div class="form-group{{ $errors->has('login_email') ? ' has-error' : '' }}">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="login_email" value="{{ old('login_email') }}">
#if ($errors->has('login_email'))
<span class="help-block">
<strong>{{ $errors->first('login_email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('login_password') ? ' has-error' : '' }}">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="login_password">
#if ($errors->has('login_password'))
<span class="help-block">
<strong>{{ $errors->first('login_password') }}</strong>
</span>
#endif
</div>
</div>
As it can be seen, just changed the email and password input names from 'email' to 'login_email' and from 'password' to 'login_password'
Any quick and efficient solutions/ideas are welcome
Instead of changing input names, just Override trait function and call it from the overriden function...
With this done, we can store a session value that tell us from where the auth attempt is coming from login or register form!
use AuthenticatesUsers, RegistersUsers {
AuthenticatesUsers::redirectPath insteadof RegistersUsers;
AuthenticatesUsers::getGuard insteadof RegistersUsers;
login as traitLogin;
register as traitRegister;
}
// Override trait function and call it from the overriden function
public function login(Request $request)
{
//Set session as 'login'
Session::put('last_auth_attempt', 'login');
//The trait is not a class. You can't access its members directly.
return $this->traitLogin($request);
}
public function register(Request $request)
{
//Set session as 'register'
Session::put('last_auth_attempt', 'register');
//The trait is not a class. You can't access its members directly.
return $this->traitRegister($request);
}
and in your View.blade file just check your errors with your Session value ...
<div class="form-group{{ $errors->has('email') && Session::get('last_auth_attempt') == 'login' ? ' has-error' : '' }}">
<label class="col-md-4 control-label">E-Mail</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
#if ($errors->has('email') && Session::get('last_auth_attempt') == 'login')
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
With this you can check if button pressed is from login ou register button
Another quick but maybe not that elegant solution would be inserting a hidden field into the login-form
<input type="hidden" name="loginform" value="1">
and then just check it with email- and password-errors in both forms.
At the login-form something like:
#if($errors->has('password') && !old('loginform'))
And at the registration-form something like:
#if($errors->has('password') && old('loginform'))
No server-side code needed.
Laravel version 5.*
I figured out:
In AuthenticatesUsers trait, change every 'email' to 'login_email' and 'password' to 'login_password'.
Also, the login attempt will use these as credentials array keys, so edit this function to:
protected function getCredentials(Request $request)
{
$credentials = $request->only($this->loginUsername(), 'login_password');
$credentials['email'] = $credentials['login_email'];
$credentials['password'] = $credentials['login_password'];
unset($credentials['login_email']);
unset($credentials['login_password']);
return $credentials;
//return $request->only($this->loginUsername(), 'login_password');
}
Now everything works fine.
In your AuthController set this in the constructor.
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct(Request $request)
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
Session::put('last_auth_attempt', $request->auth_attempt);
}
You have to send in a hidden input the value of "auth_attempt". In that way you can know in the view what you were trying to do either login or register.
Register form:
...
<input type="hidden" name="auth_attempt" value="register">
...
Login form:
...
<input type="hidden" name="auth_attempt" value="login">
...
Then in your validations or where you need it you can use the following to validate if you were trying to login or register.
<div class="form-group{{ $errors->has('lastName') && Session::get('last_auth_attempt') == 'register' ? ' has-error' : '' }}">
<label for="name">Last Name</label>
<input id="lastName" type="text" class="form-control" name="lastName" value="{{ old('lastName') }}">
#if ($errors->has('lastName') && Session::get('last_auth_attempt') == 'register')
<span class="help-block">
<strong>{{ $errors->first('lastName') }}</strong>
</span>
#endif
</div>

Categories