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;
Related
I am trying to work on a Laravel PHP project and as I am new to this framework. First step I had to do is build a Registration Form. However, when I click on the Submit button no error is given, and nothing is registered in my users table.
Here is the code for my project so far :
My users migration table up and down functions
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->boolean('sexe');
$table->integer('age');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
I added to the original two fields which are : "sexe a boolean F/M" and age
My RegisterController important functions
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Mail;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/register';
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required', 'string', 'max:255',
'sexe'=> 'required|in:male,female',
'age' => 'required|integer|max:100',
'email' => 'required', 'string', 'email', 'max:255', 'unique:users',
'password' => 'required', 'string', 'min:5', 'confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'sexe' => $data['sexe'],
'age' => $data['age'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
/**
* Override default register method from RegistersUsers trait
*
* #param array $request
* #return redirect to $redirectTo
*/
public function register(Request $request)
{
$this->validator($request->all())->validate();
//add activation_key to the $request array
$activation_key = $this->getToken();
$request->request->add(['activation_key' => $activation_key]);
$user = $this->create($request->all());
//$this->guard()->login($user);
//write a code for send email to a user with activation link
$data = array('name' => $request['name'], 'email' => $request['email'], 'activation_link' => url('/activation/' . $activation_key));
Mail::send('emails.mail', $data, function($message) use ($data) {
$message->to($data['email'])
->subject('Activate Your Account');
$message->from('s.sajid#artisansweb.net');
});
return $this->registered($request, $user)
?: redirect($this->redirectPath())->with('success', 'We have sent an activation link on your email id. Please verify your account.');
print_r($request->input());
}
}
My Routes
Route::auth();
Route::get('/home', 'HomeController#index');
Auth::routes();
Route::get('/register', 'RegisterController#create');
Route::post('/register', 'RegisterController#register');
Route::get('/', function () {
return view('welcome');
});
My User.php Model fillable
protected $fillable = [
'name','sexe','age','email','password',
];
protected $hidden = [
'password', 'remember_token',
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
}
My blade file register part (register.blade.php)
<body>
<form method="POST" role="form" action="//IJJI/resources/views/chat.blade.php">
<meta name="csrf-token" content="{{ csrf_token() }}">
<input id="name" name="name"type="text" class="form-control" placeholder="Entrez ici votre Pseudo *" value="" />
<label class="radio inline">
<input id="homme" type="radio" name="sexe" value="homme" checked>
<span> Homme </span>
</label>
<label class="radio inline">
<input id="femme" type="radio" name="sexe" value="femme">
<span>Femme </span>
</label>
<input id="age" name="age" type="integer" class="form-control" placeholder="Saisissez votre age *" value="" />
<input id="Email" name="email" type="email" class="form-control" placeholder="Saisissez votre Email *" value="" />
<input id="password" name="password" type="password" class="form-control" placeholder="Entrez votre Mot de Passe *" value="" />
<input id="confirmpassword" name="confirmpassword" type="password" class="form-control" placeholder="Confrimez votre Mot de Passe *" value="" />
<button type="submit" class="btnRegister">
Je deviens membre Gratuitement
</button>
</form>
</body>
I have done PHP artisan make auth generated the files, made .env file adequate to my MySQL database with the username and password, even checked the PhpMyAdmin configuration, but all in vain.
After 4 days of search in Google websites I can't figure out where I am wrong.
P.S : Another thing that could be wrong is that code like this :
#section
#endsection
never gets accepted and just shows like normal text on my browser.
Thanks a lot for your help
Check your laravel logs location: storage/logs you will get errors.
i have notice you are using $table->boolean('sexe') and in validation you are giving string boolen should be 0/1
'sexe'=> 'required:in:true,false',
also change in your html form to 0,1 currently you are using male, female
Are you getting error?
Besides, can you please the following line at the top of your form to see if there is any validation error or not. After that try submitting the form and see if there is any error or not!
#if(count($errors) > 0)
<div style="color:red">
#foreach ($errors->all() as $message)
<ul>
<li>{{$message}}</li>
</ul>
#endforeach
</div>
#endif
And remove the action form the form tags.
Use:
#csrf
or
{{csrf_field()}}
instead of
<meta name="csrf-token" content="{{ csrf_token() }}">
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')
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('/');
}
}