Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

george1's avatar

Laravel login doesn't seem to work - Laravel 5.7

Hi,

I started learning about Laravel 3 days ago and I reached a problem which I cannot fix.

When I register a user, the form works and the user is logged in.

The logout also works, but when I login the user which has already registered, Laravel doesn't logs him in.

Below, I am showing my code on the necessary files:

login view file

<form method="POST" action="{{ route('login') }}">
                        @csrf
                                    <input type="email" placeholder="[email protected]" class="email form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="" required autofocus>
                                    @if ($errors->has('email'))
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $errors->first('email') }}</strong>
                                        </span>
                                    @endif
                                    <input type="password" placeholder="Password" class="pwd form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" value="" required>
                                    @if ($errors->has('password'))
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $errors->first('password') }}</strong>
                                        </span>
                                    @endif
                                    @if (Route::has('password.request'))
                                        <a class="btn btn-link" href="{{ route('password.request') }}">
                                            {{ __('Forgot Your Password?') }}
                                        </a>
                                    @endif
                                    <div class="remember_me_wrapper input">
                                      <input type="checkbox" id="remember_me" class="checkbox" name="remember_me" value="scales" />
                                      <label class="remember_me_label" for="remember_me" {{ old('remember') ? 'checked' : '' }}>
                                        <span></span>
                                        Remember Me
                                      </label>
                                    </div>
                                  </div>
                                </div>
                                <input type="submit" name="submit" class="submit" value="Log in">
                              </div>
                    </form>

Login Controller file:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Valiator;
use Auth;
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 = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logouts');
    }

    public function logout(Request $request) {
        Auth::logout();
        return redirect('/');
    }

    public function checkLogin(Request $request){
        $this->validate($request, [
            'email'         => 'required|email',
            'password'      => 'required|min:8',
        ]);
    }
}

Routes (web.php)

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

    Route::resource('/', "BlogController");
    // ->condition('propability', 1);
    Route::get('auth/login', 'Auth\LoginController@getLogin');
    Route::post('auth/login', 'Auth\LoginController@login');
    Route::get('/logout', '\App\Http\Controllers\Auth\LoginController@logout')->name('logout' );

    //register
    Route::get('auth/register', 'Auth\RegisterController@getRegister');
    Route::post('auth/register', 'Auth\RegisterController@postRegister');

    Auth::routes();

    Route::any('{catchall}', function($page) {
        abort(404);
    } )->where('catchall', '(.*)');

});

Help will be much appreciated!

0 likes
29 replies
Snapey's avatar

did you write all your own login and register functionality?

Are the passwords hashed in the database?

1 like
george1's avatar

@SNAPEY - The passwords are hashed in the database, correct. It seems they use the Bcrypt hash method. What do you mean by "all my own login and register functionality?"?

king_eke's avatar

this is how i log my users in

if (Auth::attempt(['email' => $request['email'], 'password' => $request['password']])){
            if(Auth::user()->active){
    
                return redirect()->route('dashboard');
            }
            else{
                Auth::logout();

                Session::flash('danger', 'Your account has been deactivated, please contact us');

                return back();
            }
            
        }


george1's avatar

@KING_EKE - This code is written in LoginController right? Thank you for sharing your solution, but I also would like to understand what's wrong behind my issue.

king_eke's avatar

Well from what I can see, I don't think you've implemented any logic for the login method, you only did validation. And yes that code is written in the LoginController

george1's avatar

@KING_EKE - I permanently copy-pasted your code to see whether it will work. Still no luck... I thought Laravel already has implemented the logic for you, well at least from what I have seen in version 5.2.

king_eke's avatar

try this

if (Auth::attempt(['email' => $request['email'], 'password' => $request['password']])){
            dd('logged in');
            
        }

george1's avatar

@KING_EKE - Tried your code. It displays the "Log in" message, but when I go back to the home page, the user is still not logged in. I'm starting to think that the Session is not somehow being created as soon as the "Submit" button is pressed.

george1's avatar

@KING_EKE - I have watched this guy's series and he is AMAZING! I mean when the message shows up on the blank page "logged in" and I go back to the login page, I can still access it where I shouldn't. I have tested it with a newly registered user (which logs the user immediately) and I couldn't access the login or register page meaning that the user was indeed logged in.

so the problem is that when I log a user in, I can still access the login page after that meaning that the user is not being logged in.

Cronix's avatar

You only need to override the login method if you're changing how they login from the default. I don't see anything different so you probably don't need to change that at all. It will just use the default login method contained in the AuthenticatesUsers trait, that the default LoginController is using.

Is there a reason why you needed to use your own methods instead of just using the defaults? I don't see anything that you are doing that would necessitate that.

Are your sessions working at all? How are you storing user sessions?

If you are using the defaults for that (file driver), they should be created in /storage/framework/sessions. Are there any session files there? If not, is that dir writable by the web server user?

    public function __construct()
    {
        $this->middleware('guest')->except('logouts');
    }

I believe that should be logout, not logouts. You don't have a logouts method (at least that you're showing).

public function checkLogin(Request $request){

I don't think that's ever getting called. There is no default checkLogin method. There is a validateLogin method though, which is what you should be overriding. Your method isn't doing anything different from default (checks email/password), so I don't know why this method is necessary.

george1's avatar

@CRONIX - I am not trying to use my own methods for the final product but only for testing. Since I know that there are already built-in methods in Laravel, I am trying to find them and use them. Like I said (or partially said), I'm temporarily trying to make some custom methods to find where logical error lies.

Yes, there are sessions in that directory, but they don't seem to change when I log a user in. How do I check whether they are working or how do I store them? Like I said above, the sessions are not being created, since if they would, I wouldn't be able to access the login or register page which I made them not to be accessible by logged users.

I also changed the small typo (logouts to logout).

I simply don't understand why Laravel doesn't create the Session after the login has been successful.

Cronix's avatar

Look at the AuthenticatesUsers trait. That's where all of laravels methods for logging in are defined and used (in the LoginController).

What I was saying is there is no native method called checkLogin(), so I don't think your method ever gets called. It is a custom method. Laravels equivalent method is called validateLogin(). Your custom method needs to be named validateLogin(), not something you made up, unless you also go back and override the other methods that are calling validateLogin() to use yours.

Delete the sessions in that dir and try to login again. Does it create a new session file there?

The sessions get tied to a cookie. So the next place I'd check is your cookie domain settings to make sure they match the domain you're actually accessing, or else they won't be read by the browser and they won't persist. The cookie sends the encrypted session id back to laravel in every request. If the cookie isn't present, or the value doesn't match, then it can't associate the user to an actual session.

Check the network tab of your browser after you login. Do you see the session cookie? By default it's called APP_NAME_session, where APP_NAME is from your .env, unless you've explicitly set SESSION_COOKIE in your .env, then it would use that name.

george1's avatar

@CRONIX - Ok, I deleted the sessions and tried to login again. When I refresh the page (any page) a url session is being created. When I login, no session is being created. This tells me that when I login, a session is not crated.

What do you mean by "domain settings"? Where are these settings?

I also removed all the custom methods from the LoginAuthentication.

Cronix's avatar

All config settings are in the various files in the /config dir. Most of those are variables are dynamically set in the .env file. If you don't know how to set laravel up, I think you're working too fast here.

So far, I don't understand anything you're doing. There is no need (from what I can tell of your code) to alter any of the default auth settings. You should get the default auth working before trying to customize it.

I'd get rid of all of your custom code and routes and use the defaults and use the Auth::routes() route. That works out of the box unless you have larger issues (server related). Once that is working, then alter it if needed.

Snapey's avatar

Why do people insist that resolving how users login is #1 task when they start with a new framework?

george1's avatar

@CRONIX - Ok, I have removed the custom methods. I guess would be best to remove the checkLogin method.

I have checked the config/auth.php file but it seems that nothing has to change. Also, checked the .env file and seems that my Database connection works well. Am I missing anything from these configurations?

Are these considered as 'custom routes'? Route::get('auth/login', 'Auth\LoginController@getLogin'); Route::post('auth/login', 'Auth\LoginController@login'); Route::get('/logout', '\App\Http\Controllers\Auth\LoginController@logout')->name('logout' );

//register
Route::get('auth/register', 'Auth\RegisterController@getRegister');
Route::post('auth/register', 'Auth\RegisterController@postRegister');

If I remove these routes, how will Laravel know where to go, when the user clicks on the 'Log in' button?

Cronix's avatar

@GEORGE1 - Yes, those are custom routes. Laravels auth has Auth::routes() which provides all routes needed, which is mapped to the correct controllers/methods.

How do you know for sure your database is set up? You've run the migrations and know the tables are present? Can you query and actually retrieve data? Can you see your user object in it (you said you had a user created)?

All of the auth controllers should be put back to stock condition, like here: https://github.com/laravel/laravel/tree/master/app/Http/Controllers/Auth

Your /routes/web.php file should look like

    Route::resource('/', "BlogController");

    Auth::routes();

    Route::any('{catchall}', function($page) {
        abort(404);
    } )->where('catchall', '(.*)');

You shouldn't have that Route::group(['middleware' => ['web']], function (){ in there. Web routes are already using the web middleware group, so you're running the group 2x.

I think you should really watch some lessons here before continuing. https://laracasts.com/series/laravel-from-scratch-2018

george1's avatar

@CRONIX - Yes exactly, I have performed all of those (run migrations, can query and created users via the register authentication).

I brought back all the auth controllers and still, I am not able to log in. What should I do next?

UPDATE: Just seen your update. Updated the routes by removing the middleware and still nothing:/

Cronix's avatar

I'd start a new project. The reason why I say that is it would be easiest for you. You are learning laravel and have probably changed something somewhere that you aren't aware of or remember doing, and we can sit here asking a million questions about the setup. It looks like you've just started this project, so I'd just start a new one, and try to get default auth working. It works out of the box after running the various auth commands. If it doesn't, something isn't set up right and I'd start looking at whatever you're using for a dev server. I'd also watch the video series I linked to before doing anything. After you get default auth working, then add back your blogcontroller. Get that working, then add more.

george1's avatar

@CRONIX - Will do that. What about my database though? How would you link the database to the new project? I mean the migrations.

Cronix's avatar

You'd still have your custom migrations in your old project, like for blog? After you get default auth working (no custom code at all) then start to copy things over one by one. So just copy your migration file over to the new project after auth is working along with the blog controller and any other blog-related code.

All you want to do right now is get the default auth working with no other alterations. If you start mucking around and it breaks, you will have a much harder time figuring out where it went wrong (like we're doing now). So start from a known working system, then start adding your custom code back piece by piece, testing it along the way so you know at which point something breaks.

Snapey's avatar

How does this even relate to this thread?

because

I started learning about Laravel 3 days ago

and now you want to mess about with the security of the application without yet appreciating what is just working out of the box.

munazzil's avatar

Your trying both login and logout to same redirect try as like below in your login controller.

 public function logout(Request $request) {
    Auth::logout();
    return redirect('/logout');
    }

and command below one in your web.php

//Auth::routes();
george1's avatar
george1
OP
Best Answer
Level 1

@CRONIX - Thank you! I created a new project in order to experiment with the Authentication system. Seemed like I didn't create a migration, but created the tables by myself. I didn't know that Laravel required you to create a migration for your users in order for the Authentication system to work. Thank you a lot for your help and also to @king_eke for trying!

Cronix's avatar

@george1 I'm glad you got it working by taking my advice, but not sure why you marked your solution as the answer though?

Had you not been in such a hurry and read the documentation, this would have been a lot easier for you. It literally takes like a minute to get default auth working (php artisan make: auth followed by php artisan migrate assuming your db connection is set up properly). I'd highly suggest reading the docs cover to cover before using laravel. The steps for creating the auth system are pretty clear, and it already has migrations to create the users table and other things needed: https://laravel.com/docs/5.7/authentication

Please or to participate in this conversation.