How can show error message in failed login? - laravel

I make authentication system using the following command:
php artisan make:auth
It works fine. But when I try to customize the design and other stuff everything seems messy to me.i.e: When I try with wrong credential it then I can't show the message like: 'Invalid Username/password'. I inspect the all controller inside Auth folder but no detail code is there. My requirement is so simple: I just want to pass error message from controller to view and show it with my custom designed HTML template. Here is my login form:
#extends('layouts.login')
#section('content')
<div class="content">
<!-- BEGIN LOGIN FORM -->
<form class="login-form" method="POST" action="{{ route('login') }}">
#csrf
<h3 class="form-title">Login to your account</h3>
CUSTOM_ERROR_MESSAGE_IF_LOGIN_FAILED
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
<span>
Enter any username and password. </span>
</div>
<div class="form-group">
<!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
<label class="control-label visible-ie8 visible-ie9">Username</label>
<div class="input-icon">
<i class="fa fa-user"></i>
<!-- <input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username"/> -->
<input id="email" type="email" class="form-control placeholder-no-fix" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
</div>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<div class="input-icon">
<i class="fa fa-lock"></i>
<!-- <input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="Password" name="password"/> -->
<input id="password" type="password" class="form-control placeholder-no-fix" name="password" required autocomplete="current-password">
</div>
</div>
<div class="form-actions">
<label class="checkbox">
<!-- <input type="checkbox" name="remember" value="1"/> -->
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
Remember me </label>
<button type="submit" class="btn blue pull-right">
Login <i class="m-icon-swapright m-icon-white"></i>
</button>
</div>
<div class="forget-password">
<h4>Forgot your password ?</h4>
<p>
no worries, click <a href="{{ route('password.request') }}" >
here </a>
to reset your password.
</p>
</div>
<div class="create-account">
<p>
Don't have an account yet ? <a href="javascript:;" id="register-btn">
Create an account </a>
</p>
</div>
</form>
<!-- END LOGIN FORM -->
</div>
#endsection
How can I show CUSTOM_ERROR_MESSAGE_IF_LOGIN_FAILED?

First of all, believe me, we all have been there where you are now. It is frustrating when learning a new framework and how does it work.
One word of advice is to go through documentation thoroughly, there is nothing which you can't find there when it comes to Laravel. Well at least, nothing basics which you frequently need.
Now about your problem, you said:
I just want to pass error message from controller to view and show it
with my custom designed HTML template.
So I am going to take a wild guess and say that you are handling the login process yourself instead of using build-in Laravel functionality.
In case I am wrong and you are using build in laravel login functionlity then all you need to do is following:
Case 1: When you are using build in Laravel Login functionality
#if ($errors->has('email'))
<span class="invalid-feedback">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
Laravel returns the errors with keys 'email' when putting wrong credentials and try to login so just print the message using $errors->first('email') wherver you want and style it however you feel like it.
Now, if I am right and you are using custom login method:
Case 2: When you are using custom Login functionality
In your controller, you can customize your messages like so:
$messages = [
'email.required' => 'Email is required!',
'password.required' => 'Password is required!'
];
$validatedData = $request->validate([
'email' => 'required|email',
'password' => 'required|string',
], $messages);
Of course, this is just an example, you can have various validation and respective custom messages. If you want to use inbuild error messages of validation then just don't provide messages array like so:
$validatedData = $request->validate([
'email' => 'required|email',
'password' => 'required|string',
]);
When you use validate() method on $request, if validation fails, Laravel by default returns a valid error response to the blade, this response will have keys same as your request variable name and value as the error message and you can access them easily, same as in Case 1:
#if ($errors->has('email'))
<span class="invalid-feedback">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
And you are set.
Ultimately, maybe from your controller you want to return some custom error also other than validation the use following case:
Case 3: When you are using custom Login functionality and want to return some custom error message other than validation
Inside your controller use withErrors() method:
return Redirect::back()->withErrors(
[
'email' => 'Snap! you are done!'
]
);
As you might have guessed, showing this error inside your view is exactly the same as before:
#if ($errors->has('email'))
<span class="invalid-feedback">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
I hope it helps
Happy coding :)

You can output your error messages using:
#if(count($errors) > 0)
#foreach( $errors->all() as $message )
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
<span>{{ $message }}</span>
</div>
#endforeach
#endif
And you if you have a custom route, you need to redirect to the login page from your controller and passing the errors:
$errors = ['ur errors'];
return redirect()->back()->withErrors($errors);

Well, once in time I hovered over the same problem but found out that the messages were there and the only mistake was that the element which contains the error message was hidden by display:none and changed it like so .invalid-feedback { display: inline-block !important; }
After that I was able to see all the error messages. further more, I also, in LoginController, overrode the method sendFailedLoginResponse in AuthenticatesUsers
`protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
'password' => [trans('auth.password')],
]);
}`

Related

Frontend form Laravel Nova

I really like Laravel Nova but it's really complicated for a newbie like me to do something on the frontend that interacts with backend resources.
Can anyone tell me how to make a form insert data into a table from the frontend? Do I need to create a new external model? Can't interact with Nova resources?
Thanks in advance for enlightening me.
My form:
<form wire:submit.prevent="submit">
<div class="form-group">
<input type="text" class="form-control" id="code" placeholder="Introduzca código " name="code">
#error('code') <span class="text-danger">{{ $message }}</span> #enderror
</div><br>
<div class="form-group">
<input type="text" class="form-control" id="ip" placeholder="Introduzca IP " name="ip">
#error('ip') <span class="text-danger">{{ $message }}</span> #enderror
</div><br>
<div class="form-group">
<input type="text" class="form-control" id="access" placeholder="Introduzca access " name="access">
#error('access') <span class="text-danger">{{ $message }}</span> #enderror
</div><br>
<button type="submit" class="btn btn-block btn-primary">Crear Asistencia</button>
</form>
My function submit:
public function submit()
{
$this->validate([
'code' => 'required|min:4',
'ip' => 'required|min:15',
'access' => 'required|min:1',
]);
Attendance::create([
'code' => $this->code,
'ip' => $this->ip,
'access' => $this->access,
]);
session()->flash('message','asistencia creada correctamente');
return redirect(RouteServiceProvider::HOME);
}

Login Form Not Working Correctly it keeps redirecting to the same page when the users try to access their account

I have an issue with my login form where when I press the login button, the web app just redirects me to the same page. This is first time I'm making a custom login form so it's a little complex for me as I used laravel/ui in my first project. I think the problem is that the model cannot directly access the users table that's in the db. I've linked the user model to the controller but that doesn't help. If anyone can take their time to show me how to connect the login form to the users table or tell me what's wrong with my code. Here's the code that I've written so far for the login.
Login Form
<form method="post" action="/login" enctype="multipart/form-data">
#csrf
<div class="col-md-12 mt-md-0 mt-3">
<label for="email" id="email">Email</label>
<input type="email" name="email" value="{{ old('email') }}" class="form-control" placeholder="E-mail" required>
#error('email')<p class="text-danger"><small>{{$message}}</small></p> #enderror
</div>
<div class="col-md-12 mt-md-0 mt-3">
<label for="password" id="password">Password</label>
<input type="password" name="password" class="form-control" placeholder="Password"required>
#error('password')<p class="text-danger"><small>{{$message}}</small></p> #enderror
</div>
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-primary mb-4 w-50 py-2 fw-bold" >Login</button>
</div>
</form>
Routes
Route::get('login', [SessionsController::class, 'create'])->middleware('guest');
Route::post('login', [SessionsController::class, 'store'])->middleware('guest');
SessionsController
public function store()
{
$attributes = request()->validate([
'email' => 'required|email',
'password' => 'required'
]);
if (! auth()->attempt($attributes)) {
throw ValidationException::withMessages([
'email' => 'Your provided credentials could not be verified.'
]);
}
session()->regenerate();
return redirect('/')->with('success', 'Welcome');
}
I think the problem is that this form is not retrieving the data from the db that's being stored when the user registers an account.

This password reset token is invalid while trying to reset password in laravel

I am having issue in my password reset and i am getting the error of this password reset token is invalid i am unable to solve this issue:
My Controller:
class ResetPasswordController extends Controller
{
use ResetsPasswords;
}
My Routes:
\Illuminate\Support\Facades\Auth::routes();
Route::get('password/reset/{token}', 'Auth\ResetPasswordController#showResetForm');
Route::post('password/reset', 'Auth\ResetPasswordController#reset')->name('password.request');
And my View:
<form class="form-horizontal" method="POST" action="{{ route('password.request') }}">
{{ csrf_field() }}
<input type="hidden" name="token" value="{{ $token }}">
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ $email or old('email') }}" required autofocus>
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">
<label for="password-confirm" class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
#if ($errors->has('password_confirmation'))
<span class="help-block">
<strong>{{ $errors->first('password_confirmation') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Reset Password
</button>
</div>
</div>
</form>
I have also added the screen shot of my error please have a look on it also
and solution will be highly appreciated!
I has solved this problem with Laravel 7.x. I think Laravel 6.x is the same!
I create a variable $token = Str::random(64);
Next I create a record in password_resets table with value of token is: bcrypt($token)
( bcrypt() is function create password when you seed database)
Finally, link you send to email is origin $token
Because your token is incorrect, it should be a string length of 64 characters and look like this:
a8935edacb0711a304395c1f58979b545b4a636387053de6012e73048e5a60d2
And in your password_resets table in your database, it should be encrypted and look like this:
$2y$10$YOdbMZk2N7xLsfXZIuMIv.ZayZQCB21L.GXVPdtt/WMOO1hJL7enO
Change your MAIL_DRIVER= to log, truncate password_resets table (if on local), then do another password reset, then check your logs to read the email and see what the password reset token is. Copy and paste that url in your browser and see if you still get that error then we take it from there. :)
I got this issue resolved by running migrations. The password reset token column had the wrong type. It was not storing token correctly due to the wrong charset/collation of the column. Run migration and it should be fine.
or
maybe your reset password form does not contain an input for email
I had a different issue.
My passwords configuration in auth.php looks like this:
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => env('AUTH_PASSWORD_EXPIRE')
],
],
But I forgot to configure the AUTH_PASSWORD_EXPIRE .env variable on my live server.
In my case, the issue was the users table. I created the users table manually with my custom fields prior to installing laravel breeze and added the breeze required fields manually to table. I did not used breeze migration. That caused the issue.
Now I run breeze migration to create users table and then added my custom fields manually. It solved the issue.
You should also check which hash function you are using while registering the user, if the hash function for storing the user password while resetting is different from the one used to login the user you might recieve this error. In my case one was using bcrypt and one was using Hash::make

Laravel 5.5 redirect to url with anchor and with data

In my footer.blade.php i have the following code about subscribing
<!--Subscription-->
#if(Session::has('success'))
<div class="form-group has-success">
<input class="form-control form-control-success" type="text" id="input-success">
<div class="form-control-feedback">{{ Session::get('success') }}</div>
</div>
#elseif(Session::has('failed'))
<div class="form-group has-danger">
<input class="form-control form-control-danger" type="text" id="input-danger">
<div class="form-control-feedback">{{ Session::get('failed') }}</div>
</div>
#else
{!! Form::open(['route'=>'subscribe.store', 'class' => 'subscribe-form', 'novalidate' => 'novalidate']) !!}
<div class="clearfix">
<div class="input-group input-light">
{!! Form::email('email', old('email'), ['class'=>'form-control ', 'placeholder'=>'Your e-mail']) !!}
<span class="input-group-addon"><i class="icon-mail"></i></span>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true">
<input type="text" name="b_c7103e2c981361a6639545bd5_1194bb7544" tabindex="-1">
</div>
<button class="btn btn-primary" type="submit">
<i class="icon-check"></i>
</button>
</div>
{!! Form::close() !!}
<span class="form-text text-sm text-white opacity-50">Subscribe to our Newsletter to receive early discount offers, latest news, sales and promo information.</span>
#endif
In my controller i have the following function which receives the email and subscribes it correctly
public function registerNewsletter( Request $request )
{
$email = $request->input( 'email' );
$isSub = Newsletter::hasMember($email);
if($isSub) {
return redirect()->back()->with('failed', 'You have been already registered in our Newsletter system.');
} else {
Newsletter::subscribe($email);
return redirect()->back()->with('success', 'You have been registered in our Newsletter system.');
}
}
Although everything works good, i would like to page to scroll down to the footer because now it reloads and stays on top.
I've found the return redirect()->to(app('url')->previous(). '#hashid');
But there is no way to pass data among the id of the footer.
And also i've tried
return redirect()->back()->with('failed', 'You have been already registered in our Newsletter system.'). '#sitefooter';
and it didn't scroll down.
Any idea or workaround?
I've just tested this code. It will redirect you, scroll down to the anchor and will pass the data:
session()->flash('someVariable', $someData);
return redirect(url()->previous() . '#hashid');
To get stored data:
$someData = session('someVariable');
Or in a view:
{{ session('someVariable') }}

not getting checkbox element value from form

I have a small form in Laravel 5.4 which has a checkbox and a text box. The issue is that when I post the form, the checkbox value is not coming through the request. I have custom styling on the checkbox but surely it can't be that?
I've been looking at this for a while, and everything looks normal. My code is below:
<form method="post" action="{{ route('admin.settings.save') }}">
{{ csrf_field() }}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label><b>Site Name</b></label>
<p>This is the name of your LaravelFileManager instance.</p>
<input name="siteName" id="siteName" class="form-control" value="{{ \App\Helpers\ConfigHelper::getValue('site_name') }}" />
</div>
<div class="form-group">
<label><b>Footer Message</b></label>
<p>You can customise the footer message for the application.</p>
<div class="checkbox">
<label>
<input type="checkbox" name="showFooter" id="showFooter" checked="{{ \App\Helpers\ConfigHelper::getValue('show_footer_message') }}"> Show footer message
</label>
</div>
</div>
<button type="submit" class="btn btn-success"><i class="fa fa-save"></i> Save Changes</button>
</div>
</div>
</form>
My controller code is as such:
public function saveSettings(Request $request) {
$siteName = $request->input('siteName');
$showFooter = $request->input('showFooter');
ConfigHelper::setValue('site_name', $siteName);
ConfigHelper::setValue('show_footer_message', $showFooter);
return redirect()->route('admin.settings')->with('result', 'Settings saved.');
}
My route:
Route::post('settings/save', ['uses' => 'Admin\SettingsController#saveSettings'])->name('admin.settings.save');
I've also done a vardump on the $request variable and even that is missing the check box value:
array(2) {
["_token"]=> string(40) "sgyO7Kkz1ljsYEZ1G5nkj4uVbmFZqiTMbpK9P6Bi"
["siteName"]=> string(16) "File Manager 1.0"
}
It's missing the 'showFooter' variable.
Not quite sure where to go with this one. Any help appreciated.
So I got this working in the end. Using help from the comments:
public function saveSettings(Request $request) {
$siteName = $request->input('siteName');
$showFooter = $request->has('showFooter');
ConfigHelper::setValue('site_name', $siteName);
ConfigHelper::setValue('show_footer_message', $showFooter);
return redirect()->route('admin.settings')->with('result', 'Settings saved.');
}
For some reason, using $request->input('showFooter') wasn't working properly. $request->get('showFooter') brings a result when true, so adding the ternary makes it work every time.

Resources