How To show Password Wrong error to Users - php

i have a problem in showing error for users this is my Auth Login Controller :
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
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');
}
public function login(Request $request)
{
$input = $request->all();
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:8',
]);
if(auth()->attempt(array('email' => $input['email'], 'password' => $input['password'])))
{
if (auth()->user()->type == 'admin') {
return redirect()->route('admin.home');
}else if (auth()->user()->type == 'manager') {
return redirect()->route('manager.home');
}else{
return redirect()->route('home');
}
}else{
return redirect()->route('login')
->with('error','Email-Address And Password Are Wrong.');
}
$messages = [
'email.required' => 'Email is required',
'email.email' => 'Invalid email format',
'password.required' => 'Password is required',
'password.min' => 'Password must be at least 8 characters',
];
}
}
This is the LoginController from the default app in laravel i don't know why the messages of password wrong can't be showed in screen when i type wrong pass
i want to show users error if they use wrong password and this is the github link :
https://github.com/ElGrandeAchraf/skipshiftProjectCode.git
And Thank you For your attention.

It appears that the error message is not being displayed because it is being set on the redirect rather than being passed back to the view. In the else block of the login method, try replacing
return redirect()->route('login')->with('error','Email-Address And Password Are Wrong.');
With
return back()->withInput()->withErrors(['email' => 'Email-Address And Password Are Wrong.']);
This will pass the error message back to the view so it can be displayed.
Also, you can use $messages validation rules to show custom error messages, and you should call it before validate function like this:
$messages = [
'email.required' => 'Email is required',
'email.email' => 'Invalid email format',
'password.required' => 'Password is required',
'password.min' => 'Password must be at least 8 characters',
];
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:8',
], $messages);
Please note that this is just one possible solution and that it may not be the only problem you're facing in your code. You should also check the routes, views, and other related files, and make sure that everything is set up correctly.

Not sure if I was looking at the right Blade file, but in your resources/views/login.blade.php file I haven't seen anywhere that you would actually have the code to show errors. The controller doesn't do that for you automatically.
I you are returning with('error') then you should show it in Blade, something like:
#if (session('error'))
<div class="error">{{ session('error') }}</div>
#endif

Related

erro laravel "Undefined property: Illuminate\Support\Facades\Request::$email"

I'm doing a login and registration screen, the registration screen is perfect, but the login screen is giving me a headache to authenticate.
the registration is done, but as soon as I log in it gives this error...
"Undefined property: Illuminate\Support\Facades\Request::$email"
I don't know what else to do to make it work.
CONTROLLER:
<?php
namespace App\Http\Controllers;
use App\Models\Usuario;
use Illuminate\Support\Facades\Auth;
use Request;
class Usuarios extends Controller
{
public function cadastrar()
{
$usuario = new Usuario(Request::all());
$usuario->save();
return redirect('/')->with('mensagem_sucesso', 'Cadastro efetuado com sucesso!');
}
public function index()
{
return view('layout/cadastrousuario');
}
public function indexlogin()
{
return view('layout/login');
}
public function logar(Request $request)
{
if (Auth::attempt(['email' => $request->email, 'password' => $request-> password])) {
dd('voce esta logado');
} else {
dd('voce nao esta logado');
}
}
}
MODEL:
<?php
namespace App\Models;
use App\Models\Model\Request;
use DB;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
class Usuario extends Authenticatable
{
protected $table = 'usuario';
public $timestamps = false;
protected $fillable =
array(
"codigo",
"nome",
"email",
"apelido",
"senha",
"bloqueado",
"saldo",
"saldo_atual",
"admin"
);
use HasFactory;
}
ROUTE:
<?php
use App\Http\Controllers\Lancamentos;
use App\Http\Controllers\LancamentosSimplificado;
use App\Http\Controllers\Usuarios;
use Illuminate\Support\Facades\Route;
// Route = (rota)::get ou post = (method) ( '/home' = (link) , [Lancamentos = (controller) :: class, 'logar' = ( function) ;
Route::get('/', [Lancamentos::class, 'index']);
Route::get('/salvar', [Lancamentos::class, 'salvar']);
Route::get('/maisdetalhes/{codigo}', [Lancamentos::class, 'maisdetalhes']);
Route::get('/criarchat', [Lancamentos::class, 'criarchat']);
Route::post('/cadastrar', [Lancamentos::class, 'cadastrar']);
Route::post('/cadastrar-simplificado', [LancamentosSimplificado::class, 'cadastrar']);
Route::get('/criarchat', [LancamentosSimplificado::class, 'listar']);
Route::get('/chat/{codigo}', [Lancamentos::class, 'chat']);
Route::get('/chatcriado/{codigo}', [LancamentosSimplificado::class, 'chatcriado']);
Route::get('/cadastrar-usuario', [Usuarios::class, 'index']);
Route::post('/cadastrar-usuario', [Usuarios::class, 'cadastrar']);
Route::get('/login', [Usuarios::class, 'indexlogin']);
Route::post('/login', [Usuarios::class, 'logar']);
page image as soon as I click login
to start you have to make validations in the register function to be sure that the email address arrives well and is registered. i would start by modifying this function
public function cadastrar(Request $r)
{
$r->validate([
'name' => 'required|string',
'email' => 'required|email|unique:users',
'password' => 'min:6',
'password_confirmation' => 'required_with:password|same:password|min:6',
'custom_field' => 'custom validation'
]);
$input = $r->all();
$input['password'] = Hash::make($r->password);
$utilisateur = Model::create($input); //the Model == Usuario;
return redirect('/')->with([
'message' => "Cadastro efetuado com sucesso!",
'alert-type' => 'success',
]);
}
this is just a code snippet, I don't pretend to say that it's exactly what you need.the next way is the login function
if (Auth::attempt(['email' => $r->email, 'password' => $r->password])) {
// The user is active, not suspended, and exists.
$user = Auth::user();
if($user->fcm_token != Null){
$token = $user->createToken('AUTH')->accessToken;
$user->remember_token = $token;
$user->device_token = $user->fcm_token;
$user->save();
$response = [
"data"=> [
'user'=> $user,
'token'=> $token,
],
'message_fr' => 'Utilisateur connecté avec succès',
'message_en' => 'User logged successfully',
];
return response()->json($response, 200);
}else{
$response = [
'message_fr' => 'Vous êtes peut-être un robot',
'message_en' => 'You may be a robot',
];
return response()->json($response, 422);
}
} else {
$response = [
'message_fr' => 'Veuillez vérifier vos informations de connexion',
'message_en' => 'Please check your login information',
];
return response()->json($response, 422);
}
since you put a validation on the register, you are sure that the email is not only present, but also conforms to the nomenclature of an email
these two methods presented are examples taken from my source code of an available project, Good luck to you
You are using the wrong Request class. Request (Illuminate\Support\Facades\Request) that is aliased in config/app.php is the Facade, static proxy, for the bound Request class instance, Illuminate\Http\Request. If you want an instance of a Request you need to be using Illuminate\Http\Request.
use Illuminate\Http\Request;
Now via dependency injection you will have an instance of the Request class (which has magic methods to access inputs via dynamic properties). If you keep what you have then you would not be asking for an instance via dependency injection and would have to use the Facade as a Facade:
public function logar()
{
...
$something = Request::input(...); // static call to Facade
...
}

What is the best way to check active status for user whille loging in native multi-auth Laravel?

I am using laravel multi-auth. I have a table column called status. At the time of login in, I want compare user whether it is active or in active. If active only login and if not give a message 'inactive account, please contacct to administrator'.
Here is my login controller.
<?php
namespace Modules\University\Http\Controllers;
class LoginController extends Controller
{
protected $redirectTo = '/university';
public function __construct()
{
$this->middleware('guest:university', ['except' => ['universityLogout']]);
}
public function showLoginForm()
{
return view('university::login');
}
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
//attempt to log the user in
if(Auth::guard('university')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
/****Here I want check whether university status is active or not and give message if not else login*****/
return redirect()->intended(route('university.dashboard'));
}
Session::flash('failed', 'Login credential incorrect!');
return redirect()
->back()
->withInput($request->only('email', 'remember'));
}
public function universityLogout(Request $request)
{
Auth::guard('university')->logout();
return redirect(route('university.login'));
}
}
Thanks in advance.
if(Auth::guard('university')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
if( Auth::guard('university')->user()->status == 'inactive')
{
return redirect()->route('university.dashboard-inactive');
}
return redirect()->intended(route('university.dashboard'));
}
If you want to check before login is attempted you may just query the DB by the email address to check its status and then procceed with login attempt if the status is active. If you want to login anyhow regardless of the status and redirect only if inactive, something like above would work.

Laravel validating space character always failed

Trying to validate if there are only spaces in input box.
This is my validations:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use App\Rules\allAreSpaces;
class StoreUser 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 [
'email' => 'required|email|max:64',
'phone' => 'bail|required|numeric|phone_min|phone_max|unique:users|not_in:0',
'password' => [new allAreSpaces, 'required', 'min:8', 'max:16', 'confirmed'],
'password_confirmation' => 'required',
];
}
public function messages()
{
return [
'email.required' => 'Email address cannot be empty',
'email.email' => 'Enter a valid Email address',
'email.max' => 'Email address cannot exceed 64 characters',
'email.unique' => 'Email already exists',
'phone.required' => 'Mobile number cannot be empty',
'phone.numeric' => 'Mobile number has to be numeric',
'phone.phone_min' => 'Mobile number should contain a minimum 5 characters',
'phone.phone_max' => 'Mobile number cannot exceed 11 characters',
'phone.unique' => 'Mobile number already exists',
'phone.not_in' => 'Enter a valid mobile number ',
'password.required' => 'Password cannot be empty',
'password.min' => 'Password should contain minimum 8 characters',
'password.max' => 'Password cannot exceed 16 characters',
'password.confirmed' => 'Password mismatch.Retry',
'password_confirmation.required' => 'Confirm Password cannot be empty',
];
}
public function withValidator(Validator $validator)
{
$email = $this->request->get( 'email' ); // Start with
$user = \App\User::Where('email', $email)->first();
if($user && $user->activated == 0){
$row = \App\User::find($user->id);
$row->delete();
}else{
$validator->sometimes('email', 'unique:users', function ($input) {
return true;
});
}
}
}
The following is the custom rule object that i was created:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class allAreSpaces implements Rule
{
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
if(strlen($value) > 0){
if (strlen(trim($value)) == 0){
return false;
}
}
return true;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'Password cannot contain space character alone';
}
}
Initially its returning, 'Password cannot contain space character alone'. but after i type some spaces then submit it shows 'Password cannot be empty'. But i want 'Password cannot contain space character alone' if the typed characters are only spaces.
Eventhough i did use the following code, its not showing if the input has some spaces, instead it shows, 'Password cannot be empty'.
public function passes($attribute, $value)
{
return false;
}
i was wondering why is that?
Have you checked the global middleware, that is ran for all routes in your application which is set in your HTTP Kernel? These might come into play:
"By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel class. These middleware will automatically trim all incoming string fields on the request, as well as convert any empty string fields to null. This allows you to not have to worry about these normalization concerns in your routes and controllers.
If you would like to disable this behavior, you may remove the two middleware from your application's middleware stack by removing them from the $middleware property of your App\Http\Kernel class."
Laravel 5.5 Docs - Requests - Input trimming and normalization
This might be relevant as well, goes into some complications that can happen because of these middleware:
"By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel class. Because of this, you will often need to mark your "optional" request fields as nullable if you do not want the validator to consider null values as invalid. "
Laravel 5.5 Docs - Validation - A note on optional fields

laravel registration : add error to validation generated outside of validation

so this is my register controller
protected function validator(array $data)
{
return Validator;
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
register here
}
I want to add a referral system to this process basically when registering user might send a refer_id (id of a user who has referred this user to website), I'll check that refer id and if it was valid I'll do some my thing
I want to change my validation function to something like
protected function validator(array $data)
{
$validation = Validator::make($data, [
'email' => ['required' ,'email' , 'max:255', Rule::unique('users')->where('rep_id' , $this->rep->id) ] ,
'password' => 'required|string|min:6|confirmed',
'name' => 'required|max:255',
'last_name' => 'required|max:255',
'refer_id' => 'present|numeric',
]);
if(isset($data['refer_id']))
{
$refer = User::find($data['refer_id']) ;
if($refer)
{
// return error : refer id is wrong !
}
}
return $validation ;
}
my problem is this part
// return error: refer id is wrong!
how can I return registering the user with this error back to view or add this error to validation errors?
Laravel has a clean approach to do this
try this
'refer_id' => 'nullable|exists:users,id'
or may be
'refer_id' => 'present|numeric|exists:users,id'

Laravel after login keep back to login form

Good day i'm learning about laravel 5 , Now i'm trying to create a login. But, my login keep back to my login form instead of go to HomeController. Here is my script
class Loginsite extends Controller
{
public function index(){
return view::make("Login");
}
function loginproses(Request $request){
extract(Maincontroller::populateform());
/////////////////////////////////////////////////////////
$userdata = array(
'username' =>$username,
'password'=>$password
);
if(Auth::attempt($userdata) == true){
return redirect('/');
}else{
return redirect('/loginsite')->with('status', 'Username atau Password salah');
}
}
}
Routes
Auth::routes();
Route::get('/logout', 'Loginsite#logout');
Route::post('/Loginsite/loginproses', 'Loginsite#loginproses');
Route::post('/Loginsite/register', 'Loginsite#register');
Route::get('/Loginsite/', 'Loginsite#index');
Route::get('/confirm/{username}/{random}', 'Loginsite#confirm')->name('confirm');
Route::get('/', 'HomeController#index')->name('home');
and this is HomeController
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
echo "Logged In";
}
}
when i try dd(Auth::attempt($userdata) ); i get true
I'm using custom table
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Loginmodel::class,
'table' => 'Userlogin'
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
MainController
class Maincontroller extends Controller
{
//
public static function populateform(){
$input = Input::all();
foreach(array_keys($input) as $key){
$populate[$key] = $input[$key];
}
return $populate;
}
}
A test from submit
dd(Maincontroller::populateform());
return
array:3 [▼
"_token" => "YQgV3t1dc0GZrIdPboZvflBDxs7KXCEdcQkFDrD4"
"username" => "boby"
"password" => "1234"
]
Thanks in advance , sorry for my bad english
if(Auth::attempt($userdata)){
return redirect('/home');
}else{
return redirect('/')->with('status', 'Username atau Password salah');
}
try removing the true and keep it simple and check
Problem seems to be just with $username and $password, password need to be hashed. You should check this answer as well as read the documentation carefully.
I also want to suggest you some edits in code, which are important for simplification.
as in web.php you can see there is name for Home Page Route
Route::get('/', 'HomeController#index')->name('home');
Always refer that name, this will be helpful in avoiding base_url problem if any occurs or if you decide to change the route itself, you'll just need to change url which referred by name everywhere you use.
Routes
Route::post('/Loginsite/loginproses', 'Loginsite#loginproses')->name('login_process');
Route::get('/Loginsite/', 'Loginsite#index')->name('loginsite_index');
LoginSite Controller
if(Auth::attempt($userdata) == true){
return redirect()->route('home');
}else{
return redirect()->route('loginsite_index')->with('status', 'Username atau Password salah');
}
Login Form
use route() in action method with route name
<form action="{{ route('login_process') }}" method="post">
....
</form>
Add back slash before Auth::attempt($userdata) if auth not found also remove to check with true.
if(\Auth::attempt($userdata)){
return redirect('/');
}else{
return redirect('/loginsite')->with('status', 'Username atau Password salah');
}

Categories