Laravel 4: Session Flash Message Not Disappearing on Page Refresh - php

I am using same method for get and post request of login authentication like
public function login()
{
if (Request::isMethod('post')){
// Getting credentials
$username = Input::get('username');
$password = Input::get('password');
// Authenticating super admin
if(Auth::attempt(array('email'=>$username,'password'=>$password,'sysadmin'=>1))){
return Redirect::To('superadmin');
}else{
Session::flash('message', 'Invalid Credentials !');
return View::make('superadmin::login');
}
}else{
echo View::make('superadmin::login');
}
}
This is the code of login view to display error messages:
#if(Session::has('message'))
<div class="alert-box message">
<h2>{{ Session::get('message') }}</h2>
</div>
#endif
The problem is when i enter invalid credentials while login, then error message is displayed at the form but after that on manually refreshing the login page, session message does not disappear. Where as, on second time page refresh, session message disappears.
I know that this is happening because URL (referrer) remain same in my case because same method "login" is being used for both types of request (get and post).
What would be the best way to display error messages in this case so that on page refresh or automatically the message should disappear.

This is an old question but I want to explain the easiest way:
#if(Session::has('message'))
<div class="alert-box message">
<h2>{{ Session::pull('message') }}</h2>
</div>
#endif

Wouldn't this be a beter fit?
return View::make('superadmin::login')->with('message', 'Invalid credentials');
and then in your view:
#if($message)
<div class="alert-box message">
<h2>{{ $message }}</h2>
</div>
#endif
This is because you need not to flash, as you never use a redirect after a flash.

I'd rather use Session:now() instead of Session:flash() and that's it. Method now flashes messages for immediate use.

Related

Catch only one specific error in Laravel 7

I have a registration form, which contains the email and password fields. Currently, it returns the following errors in case the user does something wrong:
The email has already been taken.
The password must be at least 8 characters.
The password confirmation does not match.
However, I want that, when the user errs in the registry, only the error he made appears. I don't know if it is necessary to show the form, since there are only two input fields and a button. But, here is the code I made to return the errors:
#if(Session::has('errors') || count($errors) > 0)
#foreach($errors->all() as $error)
<div>
<h3>{{ $error }}</h3>
</div>
#endforeach
#endif
If you have an input like:
<input type="text" name="username" />
You can get the specific error, in the same view, like this:
#error('username')
<span>{{ $message }}</span>
#enderror

Laravel: Show or hide content depending on a Session variable

I'm doing a view that has a password protection. Basically when you access that resource, you have a view that indicates that you need to put a password.
The correct behavior of this should be
You access the View
The user enters the password and sends the POST form
If the method redirects back with certain value, you must see the real content of the page.
So my blade code is the following:
#if ($passedPassword = Session::get('passedPassword'))
...here goes the real/true view content
#else
<section class="questionnaire-questions">
<div>
<form
action="{{ route('questionnaire.password', ['questionnaire' => $questionnaire->id]) }}"
method="POST">
{{ csrf_field() }}
<h3 class="text-center">#lang('questionnaire.password.advice')<h3>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="goal-input-group numeric">
<label>PASSWORD</label>
<input
style='visibility: visible;'
name="password"
type="password"
>
</div>
</div>
</div>
<div class="text-center">
<button type="submit" class="goal-btn goal-btn-lg goal-btn-artic-blue">#lang('questionnaire.password')</button>
</div>
</form>
</div>
</section>
#endif
That view is rendered with the following method:
public function show(Questionnaire $questionnaire) {
$data = [];
$data['questionnaire'] = $questionnaire;
\Session::flash('passedPassword', false);
return view('questionnaires.show', array('data' => $data));
}
In the previous method I'm passing the passedPassword, but I can't find a way to pass it as a flash variable. If there is a way to add data like
return back()->with(array(
'passedPassword' => false
));
But using the view method I'll really appreciate to know how.
Then, when the user clics the button I call the next function:
public function password(Request $request, Questionnaire $questionnaire) {
if (strcmp($questionnaire->password, $request->input('password')) == 0) {
return back()->with(array(
'passedPassword' => false
));
}
}
But even when the password is correct, I got the password view, the flash/session variable never arrived to the view.
Is there something I'm missing or doing wrong?
Thanks in advance.
As Dan told me in the comments, I was setting to false the value of the session variable.
So first I remove the \Session::flash('passedPassword', false); during the show method.
Then I modify my blade logic. In my case sometimes the password is needed and sometimes not.
#if (($passwordLength === 0) || ($passwordLength !== 0 && Session::has('passedPassword')))
With that, If the resource has no password we let the user pass. Or in the case it has a password and also we have the passedPassword variable, we also let the user see the content.

redirect with old user input

I am trying to do a check to see if the user has any recorded violations or not.
I have got the flash massage to appear when the user id is entered, but I am having troubles when pressing the button, the entered ID is disappearing, I am trying to reload the page with the previously entered values.
Here is my view:
<strong>Customer ID:</strong>
<input class="form-control" type="text" name="custidno" id='cust' autocomplete="off" onkeypress="myFunction()" placeholder="Customer ID" value="{{ old('custidno') }}">
<a class="btn btn-info" href="{{ url('violationcheck') }}">Show</a>
#if(Session::has('flash_message'))
<div class="alert alert-success"><em> {!! session('flash_message') !!}</em></div>
#endif
and here is my controller:
public function violationcheck(Request $request)
{
$checked = violation::find($request->custidno);
if (!empty($checked))
Session::flash('flash_message','No violations.'); //<--FLASH MESSAGE
else {
Session::flash('flash_message','Ops, Found some violations.'); //<--FLASH MESSAGE
}
return redirect()->route('assignees.create')->withInput();
}
how do I redirect with to previous page and keep user input?
Whilst editing the controller code that you submitted about I noticed some missing curly braces in your if statement - try this and let me know if it works:
public function violationcheck(Request $request)
{
$checked = violation::find($request->custidno);
if (!empty($checked)) {
Session::flash('flash_message','No violations.'); //<--FLASH MESSAGE
} else {
Session::flash('flash_message','Ops, Found some violations.'); //<--FLASH MESSAGE
}
return redirect()->route('assignees.create')->withInput();
}

Difficulties with 'Remember me' function in laravel

So, I'm trying to create a 'remember me' function in the login process in my laravel application. I created a basic form with email, password and remember me checkbox as input, as can be seen below:
<div class="col-xs-0 col-sm-6 col-md-6 col-md-offset-3 col-sm-offset-3 col-cs-offset-5" id="content">
{{ Form::open(['route' => 'sessions.store']) }}
<div>
{{ Form::label('email', 'Email:') }}
{{ Form::email('email') }}
</div>
<div>
{{ Form::label('password', 'Password:') }}
{{ Form::password('password') }}
</div>
<div>
{{ Form::label('remember', 'Remember me:') }}
{{ Form::checkbox('remember', 'Remember-me') }}
</div>
<div>{{ Form::submit('login') }}</div>
{{ Form::close() }}
</div>
This posts to the function below. But what happens right now, is that the user is always logged in with the true parameter. What am I doing wrong?
public function store()
{
$email = Input::get('email');
$password = Input::get('password');
$remember = Input::get('remember');
if ($remember == 'Remember-me') {
if (Auth::attempt(array('email' => $email, 'password' => $password), true))
{
return Redirect::intended('/');
}
return Redirect::back()->withInput();
} else {
if (Auth::attempt(array('email' => $email, 'password' => $password)))
{
return Redirect::intended('/');
}
return Redirect::back()->withInput();
}
}
Passing true as the third parameter of Auth::attempt will remember the login on success. Additionally your $remember check makes no sense because checkbox is supposed to represent a boolean value and Input::get returns it as either 1 or null which evaluates to true or false respectively.
What you probably want is this:
public function store()
{
$input = Input::only('email', 'password');
$remember = Input::get('remember');
if (Auth::attempt($input, $remember)
{
return Redirect::intended('/');
}
return Redirect::back()->withInput();
}
One of the reasons remember me is hard to do right (and there are many) is that the first time someone logs in with the box checked they need to login conventionally and that triggers the storage that you are going to do which allows them to log in without supplying their user name and password when they come back after their session has expired and they have closed their browser etc. So the initial authentication must be totally normal except for the addition of the step where the storage for future login happens. The remember me box being checked plays no role in that initial authentication. Assuming you are going to store the data in a cookie, checking the box means that after successful authentication the cookie is created and the other logic that will be needed for remember me authentication is implemented (and I won't go into the issues around that).
Later when they come back they shouldn't need to check the box or anything like that, they should just be logged in. That's when the remember me functionality comes into play however it is that you are implementing that.
This worked for me:
$remember = (Input::has('remember')) ? true : false;
The View looks like this:
<div class="field">
<input type="checkbox" name="remember" id="remember" />
<label for="remember">Remember me</label>
</div>
Off an old tutorial I don't know where I found, but it works.

Keep modal open after validation redirect

i am currently working on a project where the login/register is handled through modal boxes (so i click the login button and a nice modal reveals with a form in).
Im using foundation 5's reveal modal to house my login form but when the form is submitted and theres a validation error the modal closes. The reason this is happening is because i am redirecting back to the route where the login form is and in that route a button needs to be clicked to fire the modal.
What i was wondering is, is there something i can set so that modal stays open if there is a validation error or exception (account not found etc.) So if there is a validation error the modal stays open.
looking for any type of solution. my code is shown below.
Login function
public function postLogin()
{
// Declare the rules for the form validation
$rules = array(
'email' => 'required|email',
'password' => 'required|between:3,32',
);
// Create a new validator instance from our validation rules
$validator = Validator::make(Input::all(), $rules);
// If validation fails, we'll exit the operation now.
if ($validator->fails())
{
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($validator);
}
try
{
// Try to log the user in
Sentry::authenticate(Input::only('email', 'password'), Input::get('remember-me', 0));
// Get the page we were before
$redirect = Session::get('loginRedirect', 'dashboard');
// Unset the page we were before from the session
Session::forget('loginRedirect');
// Redirect to the users page
return Redirect::to($redirect)->with('success', Lang::get('auth/message.signin.success'));
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
$this->messageBag->add('email', Lang::get('auth/message.account_not_found'));
}
catch (Cartalyst\Sentry\Users\UserNotActivatedException $e)
{
$this->messageBag->add('email', Lang::get('auth/message.account_not_activated'));
}
catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e)
{
$this->messageBag->add('email', Lang::get('auth/message.account_suspended'));
}
catch (Cartalyst\Sentry\Throttling\UserBannedException $e)
{
$this->messageBag->add('email', Lang::get('auth/message.account_banned'));
}
// Ooops.. something went wrong
return Redirect::back()->withInput()->withErrors($this->messageBag);
}
Login modal
<div id="myModalLogin" class="reveal-modal small" data-reveal>
<h2>Login</h2>
<form method="post" action="{{ route('login') }}">
{{-- CSRF Token --}}
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
{{-- Email --}}
<label for="email"> Email
<input type="text" name="email" id="email" value="{{ Input::old('email') }}" />
</label>
{{ $errors->first('email', '<label class="error">:message</label>') }}
{{-- Password --}}
<label for="password"> Email
<input type="password" name="password" id="password" value=""/>
</label>
{{ $errors->first('password', '<label class="error">:message</label>') }}
{{-- Remember me --}}
<input name="remember-me" value="1" id="remember-me" type="checkbox"><label for="remember-me">Remember me</label>
<hr>
{{-- Form Actions --}}
<button type="submit" class="button">Sign in</button>
I forgot my password
<a class="close-reveal-modal">×</a>
</div>
You need to create a flag variable that you will pass to your view and set it true if you want the modal to auto open and set it false if you don't want to open it:
The problem with this is that ->with() doesn't work with Redirect::back() so we need a workaround: lets pass our flag variable as an input. For this you have to get all the old input and add the new flag variable to them. Make sure that the key (your flag variable name) doesn't already exist. You can check this with a var_dump(Input::all()).
$input = Input::all();//Get all the old input.
$input['autoOpenModal'] = 'true';//Add the auto open indicator flag as an input.
return Redirect::back()
->withErrors($this->messageBag)
->withInput($input);//Passing the old input and the flag.
Now in your view you have to print this "old" input into your JavaScript condition. If it exists it will print its value: true, otherwise it will print the second argument: false.
<script>
$(document).ready(function () {
if ({{ Input::old('autoOpenModal', 'false') }}) {
//JavaScript code that open up your modal.
}
});
</script>
You can return false; when you return the validations results.

Categories