I'm adding a validation to my sign up form , the validate code is working but the errors don't shows up in the page
PHP code
public function postSignUp(Request $request)
{
$this->validate($request, [
'email'=> 'required|email|unique:users',
'first_name'=> 'required|max:120',
'password' => 'required|min:4'
]);
$email = $request['email'];
$first_name = $request['first_name'];
$password = bcrypt($request['password']);
$user = new User();
$user->email = $email;
$user->first_name = $first_name;
$user->password = $password;
$user->save();
Auth::Login($user);
return redirect()->route('dashboard');
}
Welcome.blade.php code
#section('content')
#if(count($errors) > 0)
<div class="row">
<div class="col-md-6">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
</div>
#endif
the php code is working because if i tried to register with an email that already taken it wont register but the error is that errors are not showing up in the welcome page
You are not passing the error messages back to the view.
As stated at documentation
if ($validator->fails())
{
return redirect('dashboard')->withErrors($validator);
}
You are checking with the function count($errors) but that is an object and it will always enter the condition since you are counting the object not the list itself.
Replace #if(count($errors) > 0) with #if(!empty($errors->all()))
Related
I want to store the registered email from user so if he doesnt get verification link on email to use resend function to get another email. Iam not allowing users to login so i cant get their email as Auth::$user->email, i created the hidden input to store the email but i get this error:
Undefined variable: user
This is my register function:
protected function create(array $data)
{
$user = Account::create([
'login' => $data['login'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'verifyToken'=> Str::random(40),
'active' => (env('CONFIRM_EMAIL', true)) ? 0 : 1
]);
$thisUser = Account::findOrFail($user->id);
if(env('CONFIRM_EMAIL') == true){
$this->sendEmail($thisUser);
}
return $user;
}
This is my resend function and html code to store the email:
protected function resend(Request $request)
{
$user = Account::where('email', $request->email)->first();
if($user){
$user->verifyToken = Str::random(40);
$user->save();
$this->sendEmail($user);
return back()->with('user',$user)->with('success', 'A link has been sent to your email');
}
}
<form action=" {!! route('resendEmail') !!}" method="POST">
#csrf
<input type="hidden" name="email" value="{{ $user->email }}">
<button class="btn btn-default db" type="submit" value="Submit">Resend Verification Link</button>
</form>
The error is pointing at the hidden input with value $user->email while the register function works fine and creates user in database.
I want to show logged in user data with the user of Laravel in-built class. I have used 'Session' to show the data which makes the code bulky and is not a good practice because we have to always put and flush data.
Here are my codes:
public function login(Request $req) {
$this->validate($req, [
'email' => 'required',
'password' => 'required',
]);
$email = $req->input('email');
$password = $req->input('password');
$checkLogin = DB::table('admin')->where(['email'=>$email,'password'=>$password])->first();
if(count($checkLogin) > 0){
Session::put('admin-name', $checkLogin->name);
Session::put('admin-email', $checkLogin->email);
Session::put('admin-address', $checkLogin->address);
Session::put('admin-mobile',$checkLogin->mobile);
Session::put('admin-dob',$checkLogin->dob);
Session::put('admin-pic',$checkLogin->photo);
Session::put('admin-password',$checkLogin->password);
return view('admin');
}
else {
return Redirect::route('admin-login')->with(['error'=> "Invalid email or Password!!"]);
}
}
View:
<div class="col-md-7 col-sm-7 col-xs-7 round-img-neighbour">
<p>{{Session::get('admin-name')}}</p>
<small><cite title="">{{Session::get('admin-address')}} <i class="glyphicon glyphicon-map-marker"></i></cite></small>
</div>
So you are not logging in the admin:
First log him in then access his datas:
public function login(Request $req) {
$this->validate($req, [
'email' => 'required',
'password' => 'required',
]);
$email = $req->input('email');
$password = $req->input('password');
$checkLogin = DB::table('admin')->where(['email'=>$email,'password'=>$password])->first();
if(count($checkLogin) > 0){
$adminData = Auth::loginUsingId($checkLogin->id);
return view('admin', compact('adminData'));
}
else {
return Redirect::route('admin-login')->with(['error'=> "Invalid email or Password!!"]);
}
}
In view u may access like this:
<div class="col-md-7 col-sm-7 col-xs-7 round-img-neighbour">
<p>{{$adminData->admin-name}}</p>
<small><cite title="">{{$adminData->admin-address}} <i class="glyphicon glyphicon-map-marker"></i></cite></small>
</div>
You can simply use
Auth::user();
for get the logged in user information
for ex.
if(Auth::check())
{
$loggedin_user = Auth::user();
}
So I am receiving data from a form that should reset user passwords:
Old Password: |field|
New Password: |field|
Confirm Password: |field|
And i want to be able to display a message out for the user if his old password does not match what he entered in the first field. I don't want to make an entirely new validation method and just want to throw an error to the use when i make my own if(). So how do I achieve this using the $errors variable that is available in my blade views
So here is an example of my controllers method
public function update(Request $request){
$this->validate($request,[
'oldPassword' => 'required',
'password' => 'required|min:8|confirmed'
]);
$user = Auth::user();
if(password_verify($request->newPass,$user->password)){
$user = User::find($user->id);
$user->password = bcrypt($request->newPass);
$user->save();
}else{
//the code for adding a new key to $errors variable
return back(); Or return redirect('path');
}
}
So in the view I want to this
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
You can do this in your controller:
$validator = Validator::make($request->all(),[
'oldPassword' => 'required',
'password' => 'required|min:8|confirmed'
]);
And then before your return back();, add:
$validator->after(function($validator) {
$validator->errors()->add('tagName', 'Error message');
});
With your message.
So I'm having a rather odd issue. I've created a form that allows the user to change their password.
It does change their password. But it changes their password to something that Laravel can apparently not recognise.
So if I were to use "tinker" to manually update a password to something like "testing"; I'd be able to successfully change my password. However, once I'd changed the password to something (for e.g. 123456), the form wouldn't accept the password.
When I logout of the user and try and login with the new password; it wont let me login.
So clearly Laravel is not recognising the new password.
Code is here:
View:
<div class="panel panel-default">
<div class="panel-heading">Change Your Password</div>
{{ Form::open(array('url' => 'security/change_password')) }}
<div class="form-group">
{!! Form::label('current_password', 'Enter Current Password:') !!}
{!! Form::text('current_password', null, ['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('password', 'Enter New Password:') !!}
{!! Form::text('password', null, ['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('password_confirmation', 'Confirm New Password:') !!}
{!! Form::text('password_confirmation', null, ['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Change Password', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
</div>
Controller:
public function updatePassword(UserSecurityFormRequest $request)
{
$user = Auth::user();
$current_password = $request->input('current_password');
$new_password = $request->input('password');
if (Hash::check($current_password, $user->password)) {
$user->fill([
'password' => Hash::make($request->newPassword)
])->save();
}
else{
return ('Please enter the correct password');
}
}
I also attempted to set an attribute on password in the User..
public function setPasswordAttribute($password)
{
return $this->attributes['password'] = bcrypt($password);
}
that didn't work. (edit: I then removed the above attribute) If anything it prevented the registration form (as part of Laravel's Default Auth system) from creating a password that the login form recognises.
I've checked to make sure that the form is submitting the correct details and it is. I did this by dumping all the data from the form inputs when the form is submitted successfully.
User Model:
<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\User as Authenticatable;
//use App\Http\Controllers\traits\HasRoles;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
//If register dont work or passwords arent being recognised then remove the following:
/* public function setPasswordAttribute($password)
{
return $this->attributes['password'] = bcrypt($password);
}*/
//turns dates to carbon
protected $dates = ['created_at'];
//Creates Many to Many Relationship between Users table (and model) and Roles Table (and model)
public function roles()
{
return $this->belongsToMany(Roles::class);
}
//Checks for a specific role
public function hasRole($role)
{
if(is_string($role))
{
return $this->roles->contains('name', $role);
}
return !! $role->intersect($this->roles)->count();
}
//gives the user the role
public function assignRole($role)
{
return $this->roles()->save(
Roles::whereName($role)->firstOrFail()
);
}
//Checks whether the user has a role with that permission
public function hasPermission($permission)
{
return $this->hasRole($permission->roles);
}
public function owns($related)
{
return $this->id === $related->user_id;
}
}
As you can see, I've commented out the attribute setter for passwords so that shouldn't affect it. Yet it still does not work.
Any help would be appreciated.
Thank you.
EDIT
It is not working. Massive thanks to everyone who responded and for #Steve Bauman for allowing me to indentify my mistake
Working function:
public function updatePassword(UserSecurityFormRequest $request)
{
$user = Auth::user();
$hashed_password = Auth::user()->password;
$current_password = $request->input('current_password');
$new_password = $request->input('password');
if (Hash::check($current_password, $hashed_password)) {
$user->fill([
'password' => Hash::make($request->password)
])->save();
}
else{
return ('Please enter the correct password');
}
}
Found your issue:
public function updatePassword(UserSecurityFormRequest $request)
{
$user = Auth::user();
$current_password = $request->input('current_password');
$new_password = $request->input('password');
if (Hash::check($current_password, $user->password)) {
$user->fill([
// This should be $request->password, not `$request->newPassword`
'password' => Hash::make($request->newPassword)
])->save();
} else {
return ('Please enter the correct password');
}
}
The requested variable newPassword would be empty, that's why your passwords don't work. The request field your looking for is password.
This is due to your form field using password as the input name.
You make double password hasing, first in Hash::make($request->newPassword) second in setter bcrypt($password)
Remove one and everything should be okay.
Try to use this:
bcrypt($request->newPassword);
I'm tearing my hair out over this login problem. Hopefully someone will be able to see this right off the bat and I've just been staring at it too long.
Simply put, I can create a user but can't get the same user logged into the system.
Here is the code that successfully stores the new user…
public function store()
{
//initialise new user
$user = new User();
//fill user object
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->username = Input::get('username');
$user->email = Input::get('email');
//$user->password = Hash::make('password');
$user->password = Hash::make(Input::get('password'));
$user->role_id = '2';
//submit user object
$success = $user->save();
if ($success) {
$user->save();
return Redirect::route('users.index');
}
$errors = $user->errors()->all();
return Redirect::route('users.create')
->withInput()
->withErrors($errors)
->with('message', 'You have errors on your form.');
}
Here is my login form to log in as the above user...
{ Form::open(array('url' => 'login')) }}
<ul>
<li>
{{ Form::label('username', 'Username:') }}
{{ Form::text('username') }}
</li>
<li>
{{ Form::label('password', 'Password:') }}
{{ Form::password('password') }}
</li>
<li>
{{ Form::submit('Submit', array('class' => 'btn btn-info')) }}
</li>
</ul>
{{ Form::close() }}
Here is the route:
Route::post('login', function() {
$userdata = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
//echo Hash::make('password');
if (Auth::attempt($userdata)) {
echo "success";
}
else {
//print_r($userdata);
echo "fail";
}
});
Unfortunately… when I create a user and attempt to login everything always echoes fail.
Can someone point out what I'm doing wrong?
Thanks.
DS
* ok… corrected above.
Where you have
$user->password = Hash::make('password');
it should be:
$user->password = Hash::make(Input::get('password'));
Your user creation code is giving everyone the password 'password'.