4

I am trying to send data on with() but at the view the login page refreshes but doesn't show anything. I have tried it almost with everything, I have read many questions tried almost every way.

My controller, The if condition is working .

public function authenticate(Request $request)
{
    $validator = Validator::make(Input::get(),
        [
            'password' => 'required',
            'username' => 'required'
        ]
    );
    if ($validator->fails()) {
        return redirect()
            ->back()
            ->withErrors($validator->errors())
            ->with('message', 'Invalid Username or Password.')
            ->with('form', 'login')
            ->withInput(\Input::except('password'));
    }
    $user = array(
        'name' => Input::get('username'),
        'password' => Input::get('password')
    );
    if (Auth::attempt($user)) {
        return redirect()->intended('dashboard');
    } else {
        $request->session()->put('error_message', 'Incorrect email or password');
        $request->session()->put('form', 'login');
        return redirect()
            ->back();

    }
} 

And my view is :

    <form class="login-form" method="post" style="{{{ Session::get('form', 'login') == 'login' ? 'display:block' : 'display:none;' }}}">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <h3 class="form-title">Login to your account</h3>
    <div class="alert alert-danger {{{ (Session::has('message') && Session::get('form', 'login') == 'login') ? '' : 'display-hide' }}}">
        <button class="close" data-close="alert"></button>

        <span>
            {!! Session::has('message') ? Session::get('message') : 'Please correct your fields.' !!}
        </span>

        <span>
            {!! session()->has('error_message') ? session('error_message') : 'Please correct your fields.' !!}
        </span>
    </div>
    <div class='form-group {{ $errors->has("username") ? "has-error":"" }}'>
        <!--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-envelope"></i>
            {!! Form::text('username', '', ['class' => 'form-control placeholder-no-fix', 'placeholder' => 'Username']) !!}
            <span class="help-block"> {{ $errors->first("username") }} </span>
        </div>
    </div>
    <div class='form-group {{ $errors->has("password") ? "has-error":"" }}'>
        <label class="control-label visible-ie8 visible-ie9">Password</label>
        <div class="input-icon">
            <i class="fa fa-lock"></i>
            {!! Form::password('password', ['class' => 'form-control placeholder-no-fix', 'placeholder' => 'Password']) !!}
            <span class="help-block"> {{ $errors->first("password") }} </span>
        </div>
    </div>
    <div class="form-actions">
        <!--<label class="checkbox">
        <input type="checkbox" name="remember" value="1"/> Remember me </label>-->
        <button type="submit" class="btn red pull-right">
        Login <i class="m-icon-swapright m-icon-white"></i>
        </button>
    </div>
    <br/>
    <div class="forget-password">
        <h4>Forgot your password ?</h4>
        <p>
            <a href="javascript:;" id="forget-password">Reset</a> your account login info.
        </p>
    </div>
</form>

Routes.php have these routes:

Route::group(['middleware' => 'guest'], function ()
{
    // login routes

    Route::get('/login', ['as' => 'login', 'uses' =>  "CommonController@showLogin"]);
    Route::post('/login', ['uses' =>  "CommonController@authenticate"]);

    Route::post('/reset', "Auth\PasswordController@postEmail");
    Route::get('/password/reset/{token}', 'CommonController@showReset');
    Route::post('/password/reset', 'Auth\PasswordController@postReset');

});
    Route::get('/welcome', 'HomeController@index');

Route::group(['middleware' => ['auth']], function ()
{
    // COMMONS
    Route::get('/', 'CommonController@index');
    Route::get('/dashboard', ['as' => 'dashboard', 'uses' => 'CommonController@routeDashboard']);
    Route::get('/logout', ['as' => 'logout', 'uses' =>  "CommonController@logout"]);



    Route::group(['as' => 'admin::', 'middleware' => 'role:admin'], function ()
    {

        // USERS
        Route::group(['as' => 'users::', 'prefix' => 'users'], function ()
        {
            Route::get('/', ['as' => 'manage', 'uses' => 'AdminController@showManageUsers']);
            Route::post('handle', ['as' => 'handle', 'uses' => 'AdminController@handleUsers']);

            Route::get('new', ['as' => 'new', 'uses' => 'AdminController@newUser']);
            Route::post('new', ['uses' => 'AdminController@newUserSave']);

            Route::get('edit-basic/{id}', ['as' => 'edit_basic', 'uses' => 'AdminController@editUserBasic']);
            Route::post('edit-basic/{id}', ['uses' => 'AdminController@editUserBasicSave']);

            Route::get('edit-historical/{id}', ['as' => 'edit_historical', 'uses' => 'AdminController@editUserHistorical']);
            Route::post('edit-historical/{id}', ['uses' => 'AdminController@editUserHistoricalSave']);

            Route::post('validate-username', ['as' => 'validate_username', 'uses' => 'AdminController@validateUsername']);
            Route::post('validate-email/{id?}', ['as' => 'validate_email', 'uses' => 'AdminController@validateEmail']);
        });

    });

});

On wrong username and password the message doesn't show up.

Gammer
  • 5,453
  • 20
  • 78
  • 121

3 Answers3

3

Try to add messages with $request->session()->put():

$request->session()->put('error_message', 'Incorrect email or password');
$request->session()->put('form', 'login');

And getting session data:

{!! session()->get('error_message', 'Please correct your fields.') !!}

Or

{!! session()->has('error_message') ? session('error_message') : 'Please correct your fields.' !!}

Also, check if your sessions work properly. There are few things which broke discard session data, like manually adding web middleware in 5.2.27 and higher.

Community
  • 1
  • 1
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • Undefined variable: request on the view . – Gammer May 26 '16 at 12:31
  • @Gammer, please try updated code. – Alexey Mezenin May 26 '16 at 12:31
  • Still not working, I am updating question , i am pasting the complete method of the controller and complete view, Please Please have a brief look. – Gammer May 26 '16 at 12:36
  • Do you use `web` middleware in `routes.php`. In any case, check if routes have `web` middleware with `php artisan route:list` command. If you're using files as session storage, does Laravel creates session files? If you're using database to store session data, check if rows are created. – Alexey Mezenin May 26 '16 at 12:41
  • I have just checked, Sessions are creating files, And let me again update the question for adding the all routes. – Gammer May 26 '16 at 12:44
  • Ok, also, try to manually save session with `session()->save();` clause after using `put()` methods. – Alexey Mezenin May 26 '16 at 12:46
  • Question updated, And where should i use `session()->save();` ? – Gammer May 26 '16 at 12:47
  • Please run `php artisan route:list` command. Do you see `web` in a `middleware` column? You should use `session()->save();` after `$request->session()->put('form', 'login');` – Alexey Mezenin May 26 '16 at 12:47
  • Yes every route have `web` in the `middleware` column . – Gammer May 26 '16 at 12:50
  • Really strange. Try to put something like `dd(session()->all());` after `session()->save();` clause. What's it's output? – Alexey Mezenin May 26 '16 at 12:56
  • This is the output : array:6 [▼ "flash" => array:2 [▼ "old" => [] "new" => [] ] "_token" => "g8CQwwav4YnWdyrt55sg1W4Wh2vZwGMvNdPXc9LH" "_previous" => array:1 [▼ "url" => "http://authtest.dev/login" ] "error_message" => "Incorrect email or password" "form" => "login" "_sf2_meta" => array:3 [▼ "u" => 1464267565 "c" => 1464267565 "l" => "0" ] ] – Gammer May 26 '16 at 12:59
  • Ok, so data is persisted. Try to do the same in a view, add `{!! dd(session()->all()) !!}`in the beginning of a Blade file. – Alexey Mezenin May 26 '16 at 13:03
  • View Output. array:5 [▼ "flash" => array:2 [▼ "old" => [] "new" => [] ] "_token" => "g8CQwwav4YnWdyrt55sg1W4Wh2vZwGMvNdPXc9LH" "_previous" => array:1 [▼ "url" => "http://authtest.dev/login" ] "error_message" => "Incorrect email or password" "form" => "login" ] – Gammer May 26 '16 at 13:06
  • Great! So, I guess `{!! session('error_message') !!}` and `{!! session->get('error_message') !!}` should display the message. Can you test it too, just to be sure. – Alexey Mezenin May 26 '16 at 13:09
  • Nope Nothing... Please have a llok at the view i have the following line there. ` – Gammer May 26 '16 at 13:13
  • Your code will output `'display:block'` in both these cases: when `form` is `login` and `form` is empty. You should really make simple things like `{!! session->get('error_message') !!}` work first. I don't see any reason why this code doesn't display `Incorrect email or password` message, because session has this data in a view. – Alexey Mezenin May 26 '16 at 13:21
  • Please tell me if you'll fix this. It's really interesting why this doesn't work, because session is definitely works now. – Alexey Mezenin May 26 '16 at 13:31
  • you have team viewer ? – Gammer May 26 '16 at 13:34
  • Nope, but if you want to chat, there is a chat at SO. – Alexey Mezenin May 26 '16 at 13:35
1

Use

return Redirect::back()->withErrors(['msg', 'The Message']);

and inside your view call this

@if($errors->any())
<h4>{{$errors->first()}}</h4>
@endif
Laravel User
  • 1,111
  • 1
  • 8
  • 24
0

Add web to the middleware group

Route::group(['middleware' => ['auth', 'web']], function ()

Into the below code

Route::group(['middleware' => ['auth']], function ()
{
// COMMONS
Route::get('/', 'CommonController@index');
Route::get('/dashboard', ['as' => 'dashboard', 'uses' => 'CommonController@routeDashboard']);
Route::get('/logout', ['as' => 'logout', 'uses' =>  "CommonController@logout"]);



Route::group(['as' => 'admin::', 'middleware' => 'role:admin'], function ()
{

    // USERS
    Route::group(['as' => 'users::', 'prefix' => 'users'], function ()
    {
        Route::get('/', ['as' => 'manage', 'uses' => 'AdminController@showManageUsers']);
        Route::post('handle', ['as' => 'handle', 'uses' => 'AdminController@handleUsers']);

        Route::get('new', ['as' => 'new', 'uses' => 'AdminController@newUser']);
        Route::post('new', ['uses' => 'AdminController@newUserSave']);

        Route::get('edit-basic/{id}', ['as' => 'edit_basic', 'uses' => 'AdminController@editUserBasic']);
        Route::post('edit-basic/{id}', ['uses' => 'AdminController@editUserBasicSave']);

        Route::get('edit-historical/{id}', ['as' => 'edit_historical', 'uses' => 'AdminController@editUserHistorical']);
        Route::post('edit-historical/{id}', ['uses' => 'AdminController@editUserHistoricalSave']);

        Route::post('validate-username', ['as' => 'validate_username', 'uses' => 'AdminController@validateUsername']);
        Route::post('validate-email/{id?}', ['as' => 'validate_email', 'uses' => 'AdminController@validateEmail']);
    });

});

});
VipindasKS
  • 516
  • 7
  • 15