in my laravel project, I specified 2 guards, 1 for users and 1 for admins.
everything was working properly and today I find out that I couldn't log in to the admin page.
I don't know what happened! I did not change anything!!
when I try to log in as an admin, the login page gets reloads again!
btw, for the case of users, everything works fine!
this is the code
Adminlogincontroller
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Admin;
class AdminLoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/admin';
public function __construct()
{
$this->middleware(array('guest:admin','guest:web'))->except('logout');
}
public function login(Request $request)
{
// Validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
// Attempt to log the user in
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
// if successful, then redirect to their intended location
return redirect()->intended(route('dashboard'));
}
// if unsuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email', 'remember'));
}
public function logout(Request $request)
{
$this->guard('admin')->logout();
$request->session()->invalidate();
return redirect()->route('AdminLogin');
}
public function showLoginForm()
{
return view('Admin.admin-login');
}
protected function guard()
{
return Auth::guard('admin');
}
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), $request->filled('remember')
);
}
}
blade page
<form action="/admin/login" method="post">
{{csrf_field()}}
<div class="input-field col s12">
<i class="material-icons prefix">email
</i>
<input id="icon_prefix" name="email" type="text" class="validate">
<label for="icon_prefix" style="color:#fff;">E-Mail</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">lock</i>
<input id="icon_prefix" name="password" type="password"
class="validate">
<label for="icon_prefix" style="color:#fff;">Mot de passe</label>
</div>
<p>
<input type="checkbox" class="filled-in" id="filled-in-box" />
<label for="filled-in-box" >Se rappeler de moi?</label>
Mot de passe oublié
</p>
<div class="row">
<div class="col s12">
<input type="submit" class="btn hoverable purple white-text" style="margin-top:30px;" value="connexion">
</div></div>
</form>
routes:php
Route::post('/admin/login', 'Admin\AdminLoginController#login');
Route::get('/admin/logout', 'Admin\AdminLoginController#logout');
Route::get('/admin', 'Admin\AdminController#show')->name('dashboard')
Related
I'm making my login system, through the LoginController controller, which in turn calls a request called loginRequest [I still have to update some names to Pascal]
My request only has two rules that username and password are required.
Then in a function getCredentials() I capture the username of this and validate that it is an email or not, this to give the user the option to log in both ways.
To identify if the user is actually an email, create a method 'isMail' in which I establish $factory with the content validated through an alias set to Validacion\Factory , ValidationFactory, but when executing the submit button it throws me the error :
Target [Illuminate\contracts\Validation\Factory] is not instantiable.
Could you help me?
template [login.blade.php]:
#extends('components\header')
<section class="vh-100">
<div class="container-fluid h-custom">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col-4">
<img src="{{ URL::asset('img/logo.png') }}"
class="img-fluid" height="500">
</div>
<div class="col-md-8 col-lg-6 col-xl-4 offset-xl-1">
<form action="{{route('samein.login')}}" method="POST">
#csrf
<!-- Email input -->
<div class="form-outline mb-4">
<input type="text" name="username" class="form-control form-control-lg"
placeholder="Usuario" />
<label class="form-label" for="form3Example3">Usuario</label>
</div>
<!-- Password input -->
<div class="form-outline mb-3">
<input type="password" name="password" class="form-control form-control-lg"
placeholder="Contraseña" />
<label class="form-label" for="form3Example4">Contraseña</label>
</div>
<div class="text-rigth text-lg-start mt-4 pt-2">
<button type="submit" class="btn btn-primary btn-lg"
style="padding-left: 2.5rem; padding-right: 2.5rem;">Iniciar Sesión</button>
</div>
</form>
</div>
</div>
</div>
</section>
controller[LoginController.login]
<?php
namespace App\Http\Controllers;
use App\Http\Requests\loginrequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Queue\RedisQueue;
class LoginController extends Controller
{
public function index(){
return view('login');
}
public function login( loginrequest $request ){
$credentiales = $request->getCredentials();
if( Auth::validate($credentiales) ){
return redirect()->to('login')->withErrors('auth.failed');
}
$user = Auth::getProvider()->retrieveByCredentials($credentiales);
Auth::login($user);
return $this->authenticated($request,$user);
}
public function authenticated (Request $request,$user){
return redirect('accountModule.indexusers');
}
}
and my Request[loginrequst.php]
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\contracts\Validation\Factory as ValidationFactory;
class loginrequest 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<string, mixed>
*/
public function rules()
{
return [
//
'username'=>'required',
'password'=>'required'
];
}
public function getCredentials(){
$username = $this->get('username');
if( $this->isMail($username) ){
return['email'=> $username,
'password' => $this->get('password')
];
}
return $this->only('username','password');
}
public function isMail($value){
$factory = $this->container->make(ValidationFactory::class);
return !$factory->make(['username'=>$value],['username'=>'email'])->fails();
}
}
I was reading your problem and I found interesting the way you plan to check if the email is there or not.
I know it doesn't answer your question but you could try the following:
In your Request:
public function rules()
{
return [
//
'username'=>'required',
'password'=>'required'
];
}
In your controller:
public function login( loginrequest $request ){
$field = filter_var($request->input('username'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
$request->merge([$field => $request->input('username')]);
//validate credentials
if (!Auth::validate($request->only($field, 'password'))) {
return redirect()->to('login')->withErrors('auth.failed');
}
//create a session
$user = Auth::getProvider()->retrieveByCredentials($request->only($field, 'password'));
Auth::login($user);
return redirect()->to('/');
}
don't forget to configure your web.php file, so that the routes work for you. I hope I've helped.
I am trying to implement Laravel's default email verification but whenever I change column name of users table from email to user_email Laravel stop sending verification email.
I also override default method getEmailForVerification() found in MyVerifyEmail.php file in my User Model that is returning user_email correctly.
My User Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable;
public function getAuthPassword ()
{
return $this->user_password;
}
protected $primaryKey = 'user_id';
protected $fillable = [
'user_name',
'user_email',
'user_password',
'user_phone',
'user_role_id',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = ['email_verified_at' => 'datetime',];
public function getEmailForVerification()
{
return $this->user_email;
}
public function role()
{
return $this->belongsTo(Role::class , 'user_role_id');
}
}
RegisterController Code:
public function store(Request $request)
{
$request->validate([
'name'=>'required',
'email'=>'required |email|unique:App\Models\User,user_email',
'password'=>'required',
'phone'=>'required|unique:App\Models\User,user_phone|min:10|max:15'
]);
$user = User::create([
'user_name' => $request->name,
'user_email' => $request->email,
'user_password' => Hash::make($request->password),
'user_phone' => $request->fullMobileNumber,
'user_role_id' => '9'
]);
event(new Registered($user));
$query = $user->save();
if($query){
$request->session()->flash('success','Your account has been created successfully');
return redirect()->route('login');
}
else{
return back()-> with('failed','Something went wrong. Please try again');
}
}
public function emailVerificationNotice()
{
return view('auth.verifyEmail');
}
public function emailVerificationVerify(EmailVerificationRequest $request)
{
$request->fulfill();
return redirect()->route('dashboard');
}
Register.blade.php
<form action="{{route('auth.store')}}" method="POST" id="user-registration" data-parsley-validate>
#csrf
<div id="name-wrapper" class="form-group parsley-input">
<label>Full name<span class="tx-danger">*</span></label>
<input type="text" name="name" class="form-control" placeholder="Enter your full name"
data-parsley-class-handler="#name-wrapper" data-parsley-required-message="Please enter your full name"data-parsley-pattern="^[a-zA-Z \s]+$"
data-parsley-pattern-message="Numbers & special characters aren't allowed"required>
<p class="text-danger">#error('name'){{$message}}#enderror</p>
</div>
<div id="email-wrapper" class="form-group parsley-input">
<label>Email address<span class="tx-danger">*</span></label>
<input type="email" name="email" class="form-control" placeholder="Enter your email address"
data-parsley-required-message="Please enter your email address" required autocomplete="off">
<p class="text-danger">#error('email'){{$message}}#enderror</p>
</div>
<div id="password-wrapper" class="form-group parsley-input">
<label>Password<span class="tx-danger">*</span></label>
<input type="password" name="password" class="form-control" placeholder="Enter your password"
data-parsley-required-message="Please enter your password" data-parsley-pattern="^(?=.*\d)(?=.*[a-zA-Z]).{8,}$"
data-parsley-pattern-message="Password must be 6-50 chars long, at least one letter & one number" required >
<p class="text-danger">#error('password'){{$message}}#enderror</p>
</div>
<div id="phone-wrapper" class="form-group parsley-input">
<label>Mobile number<span class="tx-danger">*</span></label>
<input type="tel" name="phone" id="user-phone" class="form-control" required>
<p id="phone-error-null" class="d-none">Please enter mobile number</p>
<p id="phone-error-msg" class="d-none"></p>
<p class="text-danger">#error('phone'){{$message}}#enderror</p>
</div>
<div class="form-group tx-12">
By clicking <strong>Create an account</strong> below, you agree to our terms of service and privacy statement.
</div><!-- form-group -->
<button type="submit" id="submit-registration" class="btn btn-brand-02 btn-block">Create Account</button>
</form>
.ENV Config
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=c1952edd7b2969
MAIL_PASSWORD=3376437f06507d
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=from#example.com
MAIL_FROM_NAME="${APP_NAME}"
actually the issue get from while overriding function getEmailForVerification().
so, i recommended you to make file MustVerifyEmail.php on Model
then copy all code from Illuminate\Contracts\Auth\MustVerifyEmail from this file and paste on new file. then use your code on new file like
public function getEmailForVerification()
{
return $this->user_email;
}
and dont forget to change User.php file
like replace
use Illuminate\Contracts\Auth\MustVerifyEmail;
to
use App\Models\MustVerifyEmail;
I'm on Laravel 5.4 and i'm trying to do a register page but data are not send in my databse... And i don't have any error.
Here is the controller : (Generate by Laravel)
namespace App\Http\Controllers\Auth;
use App\User;
use App\PostUser;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
protected $primaryKey = "id_biodiv_acteur";
protected $table = "acteur";
use RegistersUsers;
protected $redirectTo = '/pages/users';
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'surname' => 'string|max:255',
...
'picture' => 'image'
]);
}
protected function create(array $data)
{
return User::create([
'nom' => $data['name'],
'prenom' => $data['surname'],
...
'image' => $data['picture']
]);
}
}
My register.blade.php :
<div class="add-content container">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<h1>• Ajouter un utilisateur •</h1>
<div class="underline"></div>
<form action="{!! route('register') !!}" accept-charset="UTF-8" method="post" role="form">
{!! csrf_field() !!}
<div class="column-left">
<label class="has-float-label" for="name">
<input class="" type="text" placeholder="" name="name" required>
<span>Nom</span>
</label>
<label class="has-float-label" for="password">
<input class="" type="password" placeholder="" name="password" required>
<span>Mot de passe</span>
</label>
...
<label class="has-float-label" for="picture">
<input type="file" name="picture" multiple>
<span>Ajoutez des images</span>
</label>
</div>
<button type="submit" name="button">Enregistrer</button>
</form>
</div>
And a model i added to the controller (PostUser.php) :
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Events\Registered;
class PostUser extends Model
{
public $timestamps = false;
protected $primaryKey = "id_acteur";
protected $table = "acteur";
protected $fillable = [
'nom',
'prenom',
...
'image'
];
}
Laravel created route for register :
$this->get('register', 'Auth\RegisterController#showRegistrationForm')->name('register');
$this->post('register', 'Auth\RegisterController#register');
But i haven't any function call register or showRegistrationForm in RegisterController
If route('register') goes to RegisterController#create method, you can get the user-entered data in the Request parameter of that method:
protected function create(\Illuminate\Http\Request $request)
{
return User::create([
'nom' => $request->name,
'prenom' => $request->surname,
...
'image' => $request->picture
]);
}
Also, as mentioned in comments, you need to change User to PostUser or vice-versa.
I'm newbie to Laravel and got stuck with login mechanism I'm using my custom login mechanism here (not using Laravel Authentication) and there I'm not able to login with authenticate credentials.
I want to login with credentials and after login the log should be maintain in login_master and redirected to home. but it is not maintaining plus if the credentials are wrong then it should redirect back to signin.blade.php but it's redirecting to home.
Here is the code
create_login_table.php (My Login Table Structure)
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateLoginTable extends Migration
{
public function up()
{
Schema::create ('login_master',function($table)
{
$table->increments('login_id',true);
$table->integer('user_id')->unsigned();
$table->date('login_date');
$table->date('login_time');
});
// to create foreign key :)
Schema::table('login_master', function($table) {
$table->foreign('user_id')->references('user_id')->on('registration_master');
});
}
public function down()
{
Schema::dropIfExists('login_master');
}
}
LoginController (Controller for working with table)
namespace App\Http\Controllers;
use DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Validator;
class LoginController extends Controller
{
public function loginform()
{
return view('signin');
}
public function authenticate(Request $request)
{
$userdata= Input::all();
$rules= array(
'email' => 'required|email',
'password' => 'required| min:6',
);
$validator = Validator::make($userdata,$rules);
if($validator->fails())
{
redirect('/signin')->withInput(Input::except('password'))->withErrors($validator);
}
else
{
$userdata= array(
'email' => Input::get('email'),
'password' => Input::get('pwd')
);
if(Auth::validate($userdata))
{
if(Auth::attempt($userdata))
{
$email= $userdata['email'];
$password= $userdata['password'];
$live_date=Carbon::now();
$log_date=$live_date->toDateString();
$log_time=$live_date->toTimeString();
$user_id= DB::select('select user_id from registration_master where email= ? and password = ?',[$email, $password]);
$record= DB::insert('insert into login_master
(user_id, login_date, login_time) values(?, ?, ?)',[$user_id, $log_date, $log_time]);
echo $email;
echo $password;
return Redirect::intended('/');
}
}
else
{
Session::flash('error', 'Something went wrong');
return Redirect::to('signin');
}
}
}
public function logout()
{
Auth::logout();
return Redirect::to('signin');
}
}
signin.blade.php (view for login)
<html>
<head>
<title>App Name - #yield('title')</title>
#include('library')
</head>
<body>
#include('header')
<div class="form-content">
<div class="headingstyle form-title">
<h1 class="heading1">Log in!</h1>
</div>
<form method="post" action="/home">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="formgroup">
<input class="input" type="text" name="uemail"required>
<label class="label">Email</label>
</div>
<div class="formgroup">
<input class="input" type="password" name="pwd"required>
<label class="label">Password</label>
</div>
<div class="formgroup bottomstyle">
<div id="check-awesome" class="form-group checkbox">
<input type="checkbox" id="RememberMeUser" mame="RememberMeUser">
<label for="RememberMeUser">
<span></span>
<span class="check"></span>
<span class="box"></span>
Remember Me
</label>
</div><!--Login-->
<input type="submit" value="Login"><br>
<a data-dismiss="modal" class="button cancelbtn">Cancel</a><br>
<span class="links"> <a class="bottomlink" href="#">Forgot Password?</a></span><br>
<span class="links">New User
<!--<a class="bottomlink" href="#" data-dismiss="modal" data-toggle="modal" data-target="#id02">Sign Up?</a> -->
{{ Html::linkAction('SignUpController#signupform','Sign Up', array(), array('class' => 'bottomlink')) }}
</span>
</div>
</form>
</div>
<div>
#include('footer')
</div>
</body>
</html>
You will need to configure app/auth.php or dotenv to use your own custom model with the Auth Guard helper in Laravel. There you can set the model and table you want to use.
Else you could implement your own Auth helper/facade to save logged_in_user_id in session. Your custom authentication will basically confirm the passed user credentials and store the logged_in_user_id in session. Your logout method will likewise clear this id from session when called.
I have followed a tutorial to add authentication to my application. I have a login route which has the method post and the form is also submitting as a post method. But whenever I click on the login button. Laravel throws an error of MethodNotAllowed. I assume that it is getting the method as a get request but the route is a post. Error is in thecompiled.php.
Route
Route::any('signup',['as' => 'signup' , 'uses' => 'Auth\AuthController#getRegister']);
Route::any('loginForm',['as' => 'loginForm' , 'uses' => 'Auth\AuthController#showLoginForm']);
Route::post('login',['as' => 'login' , 'uses' => 'Auth\AuthController#login']);
Route::any('postRegister',['as' => 'postRegister' , 'uses' =>'Auth\AuthController#postRegister']);
View
<form id="login" method="post" action="{{ route('login') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<input type="email" placeholder="User Email" id="email" name="email" class="form-control" value="{{old('email')}}"/>
</div>
<div class="form-group">
<input type="password" placeholder="Your Password" id="password" name="password" class="form-control" {{--value="{{old('email')}}"/--}}>
</div>
<div class="row">
<div class="mj_checkbox">
<input type="checkbox" value="1" id="check2" name="checkbox">
<label for="check2"></label>
</div>
<span> remember me</span>
</div>
</div>
<div class="form-group pull-right">
<span>forget password ?</span>
</div>
</div>
</div>
</div>
<input type="submit">
</div>
</form>
{authentication code is here}
<?php namespace App\Http\Controllers\Auth;
//use \App\Http\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\LoginRequest;
use App\Http\Models\Company;
use Hash;
class AuthController extends Controller {
/**
* the model instance
public function __construct(Guard $auth, \App\User $user)
{
$this->user = $user;
$this->auth = $auth;
$this->middleware('guest', ['except' => ['getLogout']]);
}
public function getRegister()
{
return view('public-pages.Home.signup');
public function postRegister(Request $request)
{
$company = new Company;
$company-> companyName = $request -> companyName;
$company-> email = $request -> email;
$company-> password = Hash::make($request-> password);
$company-> address = $request -> address;
$company-> employeeName = $request -> employeeName;
$company-> phone_no = $request -> phone_no;
$company-> country = $request -> country;
$company-> city = $request -> city;
$company -> save();
return redirect('loginForm');
}
public function showLoginForm()
{
return view('public-pages.Home.login');
}
public function login(LoginRequest $request)
{
if ($this->auth->attempt($request->only('email', 'password')))
{
return redirect('Private-pages.Company.cmp-home');
} else {
return redirect('/login')->withErrors([
'email' => 'The credentials you entered did not match our records. Try again?',
]);
}
public function getLogout()
{
$this->auth->logout();
return redirect('/');
}
}