Redirect back with flash message for the layout template

Matanya picture Matanya · Apr 4, 2013 · Viewed 10.7k times · Source

In my controller I have a function to login a user.

In case the login was successful I can simply use return Redirect::back().

My problem starts when the credentials are incorrect and I want to redirect with a flash message.

I know I can chain the with method to the Redirect, but that would send the data to the specific view, and NOT to the layout, where the login HTML lies.

I could load a view like so:

$this->layout
     ->with('flash',$message)
     ->content = View::make('index');

But I need to redirect back to the referring page.

Is it possible to redirect while passing data to the layout?

Answer

Kylie picture Kylie · Apr 4, 2013

The Laravel Validator class handles this quite well.... The way I usually do it is to add a conditional within my layout/view in blade...

{{ $errors->has('email') ? 'Invalid Email Address' : 'Condition is false. Can be left blank' }}

This will display a message if anything returns with an error.. Then in your validation process you have...

 $rules = array(check credentials and login here...);

$validation = Validator::make(Input::all(), $rules);

if ($validation->fails())
{
    return Redirect::to('login')->with_errors($validation);
}

This way...when you go to the login page, it will check for errors regardless of submission, and if it finds any, it displays your messages.

EDITED SECTION For dealing with the Auth class.. This goes in your view...

@if (Session::has('login_errors'))
    <span class="error">Username or password incorrect.</span>
@endif

Then in your auth...something along these lines..

 $userdata = array(
    'username'      => Input::get('username'),
    'password'      => Input::get('password')
);
if ( Auth::attempt($userdata) )
{
    // we are now logged in, go to home
    return Redirect::to('home');
}
else
{
    // auth failure! lets go back to the login
    return Redirect::to('login')
        ->with('login_errors', true);

}