laravel custom login error validation - laravel

I'm doing multi authentication in Laravel in user login form the error validation is working but in my company login form the error validation is not working . please help me I'm just new in Laravel and I'm just a student. Sorry for my English
this is my code in login
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required'
]);
if (Auth::guard('company')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
return redirect()->intended(route('company'));
}
return redirect()->back()->withInput($request->only('email','remember'));
}
and this is my form where error must show
<div class="form-group row">
<label for="email" class="col-sm-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="invalid-feedback">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>

instead of:
return redirect()->back()->withInput($request->only('email','remember'));
use this:
$errors = new MessageBag(['password' => ['Email and/or password invalid.']]);
return Redirect::back()->withErrors($errors)->withInput(Input::except('password'));
also add this to the top of your controller
use Redirect;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Facades\Input;

Related

Where do I add custom verification for user registration

I have a custom regitration form where I need (users telephone number and company id) as well as email and password.
The telephone number and company id will get an api call to verify its existence in the comapny directory. If it passes then I need to allow User model to make the registration but if it fails then return a fail.
Q: where in the chain of registration should I make this api call to allow/reject the registration?
my \resources\views\auth\register.blade.php looks like this
<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">
<label for="companyid" class="col-md-4 col-form-label text-md-right">Innovations ID</label>
<div class="col-md-6">
<input id="companyid" type="text" class="form-control" name="companyid" value="" required autofocus>
</div>
</div>
<div class="form-group row">
<label for="telephonenumber" class="col-md-4 col-form-label text-md-right">Zip Code</label>
<div class="col-md-6">
<input id="telephonenumber" type="text" class="form-control" name="telephonenumber" value="" required autofocus>
</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>
here is my controller app\Http\Controllers\Auth\RegisterController.php
I would think this is where I would add my api call but not sure how to go about it.
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller{
use RegistersUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct(){
$this->middleware('guest');
}
protected function validator(array $data){
return Validator::make($data, [
'companyid' => ['required', 'string', 'max:255'],
'telephonenumber' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
return User::create([
'companyid' => $data['companyid'],
'telephonenumber' => $data['telephonenumber'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
this is my user model app\User.php
protected $fillable = [
'companyid', 'telephonenumber', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
You need to do it in the create method of the RegisterController.
You can make api calls within create method using the Http facade. But you need to have guzzle as dependency in your project. You can pull it using composer.
composer require guzzlehttp/guzzle
Then you can make the api calls
protected function create(array $data)
{
//Remember to import the use statement
//use Illuminate\Support\Facades\Http; at top
$response = Http::get('http::/example.com');
//Need to stop further execution by throwing an exception
//If the verification via api call fails
//abort_unless($response->verified = true, 419);
return User::create([
'companyid' => $data['companyid'],
'telephonenumber' => $data['telephonenumber'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
Laravel docs: https://laravel.com/docs/8.x/http-client#making-requests

laravel hyn/multi-tenancy override login method using tenant db redirect again login page try to redirect homepage

In hyn/multi-tenancy after overriding the login method in LoginController and within this method connect the tenant database. It login successfully if I print the login results but when I redirect it to homeController it again redirects to the Login Page and doesn't go to the home page. I use
https://github.com/peartreedigital/boilerplate
example only change in loginController which is
class LoginController extends Controller
{
use AuthenticatesUsers;
public function username()
{
$login = request()->input('identity');
$field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
request()->merge([$field => $login]);
return $field;
}
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function validateLogin(Request $request)
{
$messages = [
'identity.required' => 'Email or username cannot be empty',
'email.exists' => 'Email or username already registered',
'username.exists' => 'Username is already registered',
'password.required' => 'Password cannot be empty',
];
$request->validate([
'identity' => 'required|string',
'password' => 'required|string',
'email' => 'string|exists:users',
'username' => 'string|exists:users',
], $messages);
$domain_name = $request->get('domain_name');
$usernameatacc = $request->get('identity');
$password = $request->get('password');
$hostname = DB::table('hostnames')->select('*')->where('fqdn', $domain_name)->first();
$dbname = DB::table('websites')->select('uuid')->where('id', $hostname->website_id)->first();
Config::set("database.connections.tenant", [
"driver" => 'mysql',
"host" => '127.0.0.1',
"database" => $dbname->uuid,
"username" => 'root',
"password" => ''
]);
Config::set('database.default', 'tenant');
DB::purge('tenant');
DB::reconnect('tenant');
}
public function login(Request $request)
{
$this->validateLogin($request);
$user_data = User::where('email', $request->get('identity'))
->first();
$matchPwd = Hash::check($request->get('password'), $user_data->password);
if ($matchPwd == '1') {
// print_r($user_data);
// Here What can I do????? Please help
}else {
return redirect()->back()->withErrors($user_data);
}
}
protected function guard()
{
return Auth::guard();
}
}
My login form in login.blade.php is
<form method="POST" action="{{ route('login') }}">
#csrf
<div class="form-group row">
<label for="domain_name" class="col-sm-4 col-form-label text-md-right">{{ __('Domain Name') }}</label>
<div class="col-md-6">
<input id="domain_name" type="domain_name" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="domain_name" value="{{ old('domain_name') }}" required autofocus>
#if ($errors->has('domain_name'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('domain_name') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="identity" value="{{ old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</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{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>
#if ($errors->has('password'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</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>
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
</div>
</div>
</form>
You can redirect user after login with defining either method of redirectTo() or property of $redirectTo.
protected function redirectTo()
{
if (User::check()) {
return route('home');
}
}
or
protected $redirectTo = '/';
Be careful about referring to the name that you've assigned in the route file (default: web.php).

How to change password?

I want to edit form update only address, email and password. How to change password? The old password is important.
edit.blade.php
<form method="POST" action="{{ route('update') }}">
#csrf
{{ method_field('PATCH') }}
<div class="form-group row">
<label for="email" class="col-md-1 col-form-label text-md-right">{{ __('Email') }}</label>
<div class="col-md-5">
<input id="email" type="text" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') ? : user()->email }}" required autocomplete="email" autofocus>
#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-1 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-5">
<input id="password" type="text" class="form-control #error('password') is-invalid #enderror" name="password" value="{{ old('password') }}" required autocomplete="password" autofocus>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="address" class="col-md-1 col-form-label text-md-right">{{ __('Address') }}</label>
<div class="col-md-5">
<textarea id="address" type="text" class="form-control #error('address') is-invalid #enderror" name="address" required autocomplete="address" autofocus>{{ old('address') ? : user()->address }}</textarea>
#error('address')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-1">
<button type="submit" class="btn btn-block btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
Route
Route::post('update', 'Auth\RegisterController#sqlupdate')->name('update');
RegisterController
public function sqlupdate(Request $request)
{
Auth::user()->update([
'address' => $request['address'],
'email' => $request['email'],
]);
$hashedPassword = auth()->user()->password;
if (Hash::check($request->oldpassword, $hashedPassword)){
$user = User::findOrFail(Auth::id());
$user->password = Hash::make($request->password);
}
return redirect()->back();
}
Just read the below code carefully :-
/**
* Admin My profile : Password update.
*
* #param Request $request
* #param $id
* #return \Illuminate\Http\Response
*/
public function updatePassword(Request $request,$id = 0)
{
$validate = Validator::make($request->all(),[
'old_password' => 'required',
'password' => 'required|confirmed|min:8',
'password_confirmation' => 'required|min:8',
]);
$getUserData = Admin::where('id',$id)->first();
if($getUserData === null) {
return redirect()->back()->with([
'status' => 'warning',
'title' => 'Warning!!',
'message' => 'Invalid Admin ID.'
]);
}
$validate->after(function ($validate) use ($request,$getUserData,$id) {
if(!Hash::check($request->get('old_password'),$getUserData->password)){
$validate->errors()->add('old_password', 'Wrong old password');
}
});
if($validate->fails()){
return redirect()->back()->withErrors($validate)->withInput();
}
try{
$getUserData->update([
'password' => Hash::make($request->get('password'))
]);
return redirect()->back()->with([
'status' => 'success',
'title' => 'Success!!',
'message' => 'Admin password updated successfully.'
]);
}catch (Exception $e){
return redirect()->back()->with([
'status' => 'error',
'title' => 'Error!!',
'message' => $e->getMessage()
]);
}
}
With the above method you'll get the idea of how we update password, this is from one of my project i've created three field for that here is the screenshot of view :-
I hope this will help
Further more update here is the small snippet for update method
specially
$getOldPassword = User::where('id',$id)->first();
if($request->get('password') === null){
$password = $getOldPassword->password;
}else{
$password = Hash::make($request->get('password'));
}

I have generated User Login and Register through make:auth, now i want to update details

I have generated user auth through make:auth, which doesn't have edit details field, now I want to edit details such as email and contact, and others leave as disabled. I have tried to copy code from RegisterController i just changed create method to update method, If you have ready template for edit details please share me, I have searched many ready templates but not found, I just want template, which will be compatible with generated Auth or solution to my problem, because now it is not updating the details
1) View: edit_profile.blade.php
<form method="POST" action="/profile">
#csrf
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" disabled type="text" class="form-control" value='{{$user->name}}' name="name">
</div>
</div>
<div class="form-group row">
<label for="username" class="col-md-4 col-form-label text-md-right">{{ __('Student Number') }}</label>
<div class="col-md-6">
<input id="username" disabled type="text" class="form-control" name="username" value="{{$user->username}}">
</div>
</div>
<div class="form-group row">
<label for="age" class="col-md-4 col-form-label text-md-right">{{ __('Age') }}</label>
<div class="col-md-6">
<input id="age" disabled type="text" class="form-control" name="age" value="{{$user->age}}"
required> #if ($errors->has('age'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('age') }}</strong>
</span> #endif
</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{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{$user->email}}"
required> #if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span> #endif
</div>
</div>
<div class="form-group row">
<label for="contact" class="col-md-4 col-form-label text-md-right">{{ __('Contact Number') }}</label>
<div class="col-md-6">
<input id="contact" type="text" class="form-control{{ $errors->has('contact') ? ' is-invalid' : '' }}" name="contact" value="{{$user->contact}}"
required> #if ($errors->has('contact'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('contact') }}</strong>
</span> #endif
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Update Details') }}
</button>
</div>
</div>
</form>
2) Controller: ProfileController
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use Image;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Carbon;
class ProfileController extends Controller
{
public function profile(){
return view('pages.profiles.profile', array('user' => Auth::user()) );
}
public function update_avatar(Request $request){
// Handle the user upload of avatar
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->crop(300, 300)->save( public_path('/storage/images/avatars/' . $filename ) );
$user = Auth::user();
$user->avatar = $filename;
$user->save();
}
return view('pages.profiles.profile', array('user' => Auth::user()) );
}
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|string|email|max:255|unique:users',
'contact' => 'numeric|digits_between:7,15',
]);
}
public function edit(){
return view('pages.profiles.edit_profile', array('user' => Auth::user()) );
}
public function update(array $data){
return User::update([
'email' => $data['email'],
'contact' => $data['contact'],
]);
}
}
Routes
//User Profile
Route::get('/profile', 'ProfileController#profile');
Route::post('profile', 'ProfileController#update_avatar');
Route::get('/profile/edit', 'ProfileController#edit');
Route::post('profile/edit', 'ProfileController#update');
There are a few issues that I've noticed.
You're ProfileController#update method accepts an array but it won't be getting passed an array.
You're not calling update on the authenticated user.
You're posting to /profile which looking at your routes if for updating the avatar and not the user data.
Change your form to be:
<form method="POST" action="/profile/edit">
Change your update method to:
public function update(Request $request)
{
$data = $this->validate($request, [
'email' => 'required|email',
'contact' => 'required',
]);
auth()->user()->update($data);
return auth()->user();
}
Documentation for Laravel's Validation
public function update(Request $request)
{
//check validation
Auth::user()->update($request);
return true;
}

Laravel always sets the default value

I am trying to do registration with user profile picture upload.(I am forced to do it this way)
I created the migration like this:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('nom');
$table->string('prenom');
$table->string('type')->default('visiteur');
$table->boolean('confirme')->default(false);
$table->string('email')->unique();
$table->string('password');
$table->string('photo_url')->default('default_photo_profile.jpg');
$table->rememberToken();
$table->timestamps();
});
the create function :
$request = request();
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
and the form for the file field is like this:
<div class="form-group">
<label for="photo_url">Photo profile</label>
<input type="file" name="photo" class="form-control-file" id="photo_url">
</div>
everything is working fine except the photo_url field, it always sets the default value in the migration and not the value I set in the create function.
$fullname is initiated and already declared.
the entire form :
<form method="POST" action="{{ route('register') }}" aria-label="{{ __('Register') }}" enctype="multipart/form-data">
#csrf
<div class="form-group row">
<label for="nom" class="col-md-4 col-form-label text-md-right">Nom</label>
<div class="col-md-6">
<input id="nom" type="text" class="form-control{{ $errors->has('nom') ? ' is-invalid' : '' }}" name="nom" value="{{ old('nom') }}" required autofocus>
#if ($errors->has('nom'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('nom') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="prenom" class="col-md-4 col-form-label text-md-right">Prénom</label>
<div class="col-md-6">
<input id="prenom" type="text" class="form-control{{ $errors->has('prenom') ? ' is-invalid' : '' }}" name="prenom" value="{{ old('prenom') }}" required autofocus>
#if ($errors->has('prenom'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('prenom') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">Email</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required>
#if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">Mot de pass</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>
#if ($errors->has('password'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">Mot de pass confirmation</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
</div>
</div>
<div class="form-group">
<label for="photo_url">Photo profile</label>
<input type="file" name="photo" class="form-control-file" id="photo_url">
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Envoyer
</button>
</div>
</div>
</form>
What is the problem?
Assuming you have a value for $photo_url, make sure you have 'photo_url' in your $fillables.
When you have $fillables, it only inserts (via User::create) what has in that array, otherwise it doesn't submit for that variable.
Your $fillables should look like this:
$fillables = ['nom','prenom','type','confirme','email','password','photo_url'];
Add 'photo' in $fillable array in User model:
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'photo_url',
];
so according to your code in your model you have to add the photo_url in $fillable array like below.
$fillables = ['nom','prenom','type','confirme','email','password','photo_url'];
okay now there are 3 ways to do it with $fillable is first way and you are doing it right now.
2nd way:
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
}
else
{
$fullname = "default_photo_profile.jpg";
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
and in your migration change this $table->string('photo_url')->default('default_photo_profile.jpg'); to $table->string('photo_url');
3rd way:
$fullname = "default_photo_profile.jpg";
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
okay these are the ways to do it. i would prefer first and second way 3rd one is lengthy.
Note: for 2nd and 3rd case you have to change your migration from this $table->string('photo_url')->default('default_photo_profile.jpg'); to $table->string('photo_url');
Hope you get it.

Resources