171 thoughts on “How to Make User Login and Registration Laravel 5.1

  1. Jelly says:

    Hi, this is great tutorial, would be amazing to add code example on github to have everything on one place, and maybe other people could extend/improve your code

    Thank you.

    Liked by 1 person

    • Note to everyone: This tutorial is for Laravel 5.1.11, which as of 10/16/2015 is the latest stable release. If you are using the master, there may be differences that I have not accounted for. When the next release is made, I will update the tutorial if necessary.

      Thanks for the positive feedback, I appreciate your encouragement. I will keep your suggestion in mind for the future. Thanks again.

      Like

      • Thanks for the Tutorial.After press submit i receive this on page?
        Object not found!

        The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.

        If you think this is a server error, please contact the webmaster.
        Error 404
        localhost
        Apache/2.4.12 (Win32) OpenSSL/1.0.1m PHP/5.6.11

        Like

      • Frank says:

        The error message is the same like the 404 of basharmomin77, but in my case it’s in german. So it doesn’t look like a laravel message. I think there is no connection between register.blade.php and routes.php.

        Like

      • If you follow the tutorial and have your routes and views set correctly, it will work with a fresh install of Laravel. If it is not working you may have an environment issue. I have never seen an error message from Laravel that was written in German….

        Like

    • Just an update, I did add the views to Github in two separate gists, so it is really easy to grab the view code. The controller code is already provided out of the box, so no need to provide that. The routes are given in the tutorial and are easy to copy in one go. Thanks everyone for all the great feedback.

      Like

  2. Hi Casey. Look for typos in your view, especially in @extends(‘layouts.master’) and @section(‘content’). Make sure you folder structure is correct. You should have a layouts folder in views, with a master.blade.php file in it. Also I had a typo in the tutorial that made the name of the reg folder unclear. I’ve corrected that, so you just need make sure that you have a folder named reg inside of views that will hold the register.blade.php view.

    Remember to name your view files viewname.blade.php. Here is a link to the docs on views. Also a good laracasts video for basic routing and views. It’s free.

    To get to your view, the url: localhost:8000/projectfolder/your-route-to-controller-action should work. The controller action should return the view. In the case of reg in my tutorial, If you are able to load the welcome page, localhost:8000/projectfolder/reg should work.

    In the RegistrationController, you want the register method to return view(‘reg.register’).

    Syntax errors in views will cause white pages. Route/controller/view folder errors will cause view not found errors.

    I hope this helps.

    Like

  3. casey says:

    i solved the problem – i had successfully logged in so to view the registration i had to log out, thanks for you’re reply!

    Like

  4. Tutless says:

    hi

    i got an error

    [2015-06-27 07:49:48] local.ERROR: exception ‘Symfony\Component\Debug\Exception\FatalErrorException’ with message ‘Trait ‘App\AuthTraits\RedirectsUsers’ not found’ in B:\projects\laravel5\app\Http\Controllers\Login\LoginController.php:15
    Stack trace:
    #0 {main}

    Like

    • add use App\AuthTraits\RedirectsUsers; to the top of the file and you should be good. Or check the namespace in RedirectsUsers.php, it should be App\AuthTraits. Also note that you must use uppercase A for App. One of these solutions should solve your problem. If none of those work, try running composer dump-autoload from the command line.

      Like

      • Hi I have checked and i have namespaces and imports right although I am still getting this error…

        Whoops, looks like something went wrong.

        1/1
        FatalErrorException in RegistrationController.php line 17:
        Trait ‘App\AuthTraits\RedirectsUsers’ not found
        in RegistrationController.php line 17

        Many thanks for your help

        Like

      • Is your AuthTraits folder directly under the app folder? And is the RedirectsUsers.php file inside of the AuthTraits folder? Do you have the following inside your RedirectsUsers file:

        namespace App\AuthTraits;

        trait RedirectsUsers
        {
        /**
        * Get the post register / login redirect path.
        *
        * @return string
        */
        public function redirectPath()
        {
        if (property_exists($this, ‘redirectPath’)) {
        return $this->redirectPath;
        }

        return property_exists($this, ‘redirectTo’) ? $this->redirectTo : ‘/home’;
        }
        }

        Like

    • Hi Daniel. If I understand your question, you are asking how to leave a route/controller open so that it does not require login. A route/controller will not require login by default, so if you want a route that is wide open, it will operate that way normally, you don’t have to do anything special to it.

      Like

      • in my case i have a website and i build using laravel 5.1
        how i set only home.index that doesnt need login, but if user access admin page it need login

        Like

      • I will be covering that in a separate tutorial. It would take to too long to explain in a comment. The tutorial will be a bout Middleware implementations, so you can look that up if you need to work on it immediately.

        Like

  5. Mushki says:

    Hi,

    I noticed that oddly enough (at least for me), the logout function in LoginController.php gets triggered regardless of the middleware. I added a small check to compensate:

    public function logout() {
    if(Auth::guest()) return redirect(‘/’);

    Auth::logout();
    return redirect(property_exists($this, ‘redirectAfterLogout’) ? $this->redirectAfterLogout : ‘/’);
    }

    The real question is, why does logout get triggered regardless of the guest middleware (for me)?

    Like

  6. leo says:

    hy bill, nice tutorial, but after logout i still have an access into my other controller that require login first, where is my mistake?

    please make a tutorial that describes the page that requires a login and pages that do not need to login, example is homepage and admin page

    Like

    • Not sure I understand the question. The tutorial is set up to use email and password for credentials. If you want to change to username instead of email, that should be a relatively easy change, just make the changes to the form and the LoginController. If you want a form where the user can enter either an email or a password, this is of course possible, but beyond the scope of this tutorial.

      Like

  7. Hi, really nice tutorial, you saved my day!

    2 things…

    1)

    I’m having trouble understanding and getting the “error” part to work.
    Either he default validation errors in resources/lang/ seem to override this getFailedLoginMessage method or I’m doing something wrong. I’ve dd(‘test’) in the getFailedLoginMessage method and It’s not even calling that method.

    public function postLogin(Request $request)
    {
    $this->validate($request, [
    ’email’ => ‘required|email’, ‘password’ => ‘required’,
    ]);

    $credentials = $this->getCredentials($request);

    if (Auth::attempt($credentials, $request->has(‘remember’))) {
    return redirect()->intended($this->redirectPath());
    }

    return redirect($this->loginPath())
    ->withInput($request->only(’email’, ‘remember’))
    ->withErrors($this->getFailedLoginMessage());
    }

    And what does ’email’ mean in the section below? I understand $this->getFailedLoginMessage, that doesnt work… hehe.. but what is the ’email’ part for?

    ->withErrors([
    ’email’ => $this->getFailedLoginMessage(),
    ]);

    2)

    I was not able to get the logout() method to work, it just redirected me back to the same page without being called at all, verified through dd(). I had to rename it getLogout() to make it work.

    Do you know why?

    Build laravel/laravel 5.1.7 and .8

    Many thanks Bill!

    Like

    • It all works for me. Thank you for listing the version number. I did my build with Laravel 5.1, so it’s possible that something has changed. When I get time, I will rebuild in the latest version and see if there are any problems. I believe ’email’ refers to the input from the request, but keep in mind I did not write that part, it was part of the AuthenticatesAndRegistersUsers traits from the original build. I just moved the code up to a login controller to make it easier to work with. If you find your solution, please come back and add it via comment, so others will know if this is a version problem or just a bug on your part. Thanks!

      Like

  8. Thank’s bill, but i have a little problem here,
    When i try to logout I get this error :

    ErrorException in LoginController.php line 97: Undefined property: App\Http\Controllers\Login\LoginController::$redirectAfterLogout

    Like

  9. Hi Bill.

    This tutorial is good for me, but am getting this error.

    Whoops, looks like something went wrong.

    QueryException in Connection.php line 636: SQLSTATE[42S22]: Column not found: 1054 Unknown column ’email’ in ‘where clause’ (SQL: select count(*) as aggregate from `users` where `email` = avc@gmail.com)

    Like

    • There a number of reasons why this can happen. If you have a syntax error in your login.blade.php file for example or the environment is not setup properly, which would probably return an error and not a blank page. I always use local host entries with my projects, so my urls look like:

      myproject.com/auth/login

      and it works perfectly fine.

      Like

  10. I’m having trouble at register, i want to access the registration form when and only the admin is logged in.. the access for the registration is guest by default, but when i add middleware=>auth into the registration route, it redirects me at my home… please, i need your help, thanks in advance…

    Like

  11. francis tulabing says:

    Hey BIll

    I checked my authcontroller and it doesn’t have a getlogin function which i thnk that causes the route to return a blank page.

    howsthat should go?

    Like

  12. chrissy says:

    Nice Tutorial!

    im having trouble when i try to click the login button, im redirected to a url which is not found how am i able to solve this problem..

    any advice will be appreciated
    TIA.

    Like

    • You need to set the redirectTo property on your AuthController:

      private $redirectTo = ‘/’;

      That is of course assuming you have a route setup for ‘/’. You can set the redirectTo property to any valid uri.

      Like

  13. bumalok says:

    Hi,

    im new to laravel. i successfuly installed Laravel and getting the welcom page from laravel.

    but when i tried to follow your added codes and put localhost/laraproj/public/auth/login it says the not found

    thnx in advance

    Like

  14. Im having troubles viewing pages after something is inside the database. When I remove the item in the database it works fine but after registrering or manually inserting into database it gives me : NotFoundHttpException in RouteCollection.php line 143:

    Like

  15. chrissy says:

    Hi!

    why im getting this error whenever i try to login

    TokenMismatchException in C:\wamp\www\LaravelFive\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php line 53:

    Like

  16. Pradhan says:

    Hi,

    Thanks for the nice tutorial,

    But I have a different senario here, I have two tables named as users and admin that store the user credentials and the admin credentials respectively, And I want to create the different login view and postLogin functionality that acts independent to one another, such as login from admin hits to the admin dashboard and login from user section hits to the user dashboard.

    I followed the suggestion from http://stackoverflow.com/questions/31270025/laravel-5-how-to-work-with-authentication-on-two-different-login-forms-with-diff

    But when the users login in the user can also can view the admin dashboard and when the users log out the admin also gets log out.

    Could please help me out with this ?

    Great Thanks…

    Like

    • I don’t think it’s wise to have separate logins for the reasons that you are experiencing. My tutorial did not cover roles, but that’s something I’ve been working with. The simple version would be to create a is_admin field on the user record, detect that on login and redirect to the admin page. If you have multiple admin roles, then you need a separate data structure. Either way, that is beyond the scope of this tutorial.

      Like

      • Leon says:

        This is confusing me too! I don’t have an appTraits folder, or an illuminate/foundation folder in vendors, and cannot find any reference to AuthenticatesAndRegistersUsers other that in the AuthController. what does all this refer to?

        Like

      • You have to drill down to find the parts you will recognize, such as getLogin. That is found in the AuthenticatesUsers trait, which is found in your vendor/laravel/framework/src/Illuminate/Foundation/Auth folder. I recommend re-reading the tutorial and then following that up with reading about traits in PHP. This was tough for me to get initially too, but once you understand how traits work and how they help keep your code clean. It’s gotten a bit more complicated since they added the ThorttlesLogins trait, but that is a really cool feature. Just keep working with it, eventually you will get it.

        Like

    • You would need to change the getLogin method on the AuthenticatesUsers trait to point to the view you want. Here is a tip. I prefer not to make changes to the out of the box traits that ship with Laravel. Instead, I overwrite the method in the AuthController. That way, when I run composer update, I’m not overwriting custom code.

      Like

  17. Hey Bill,

    Thanks for this straight forward tutorial. Very simple and easy to follow.

    One thing I did run into though.

    I think there’s a typo in your tutorial that is causing an error when you visit yourapp.com/auth/login

    “Let’s create a login.blade.php file within the app/resources/views/login” should be “app/resources/views/auth”?

    I was following the tutorial and created a “login” folder to put login.blade.php in it. When visiting yourapp.com/auth/login I get the following error

    InvalidArgumentException in FileViewFinder.php line 137:

    Once I moved login.blade.php into the app/resources/views/auth folder everything was fine.

    Like

  18. bufei says:

    Hi Bill, great tutorial!

    I am new to laravel.

    I follow ur tutorial and it work. but i facing a weird situation. When i register new user it keep saying i havent fill the required form( like name). how to solve this problem?

    Like

    • This can happen when the in put name does not match the name you have set in validation. In the case of the tutorial, it is looking for name, email, and password. Make sure that matches what you are trying to validate.

      Like

  19. Great job, this tutorial let me know more about Laravel 5.1.

    I can do the Register, and new user store in the to database.

    but for the login, I got some error after user login when I try to get some user information

    $user = Auth::user()->name;
    return $user;

    It said: ErrorException in ArticlesController.php line 19: Trying to get property of non-object

    and I can logout.

    thx Bill

    Liked by 1 person

    • The problem seems to be in your ArticlesController. That is not native to the tutorial. Make sure you are using the Auth facade in that controller: use Illuminate\Support\Facades\Auth;

      Like

      • thx Bill, I am not sure, because I am using Illuminate\Support\Facades\Auth; the tutorial is base on 5.0, but I am starting in 5.1.17…….

        I am still finding the answer, and will post here if I fixed it.

        Like

    • You’re not really giving me enough information to help you. Is it a permissions issue with your server? What is the url of the page returning forbidden? Do you have a mistake in the middleware?

      Like

      • The url of my register form page is /auth/register as the same as this page that ha only “Forbidden” on it. I don’t think it’s a server permission issue. How do I check for a middleware mistake?

        Like

    • did you follow this tutorial from a fresh install of laravel 5.1? did you run the migration, add the route files? Did you set the .env settings to your DB? The middleware is set in the constructor of the auth controller and should be:

      $this->middleware(‘guest’, [‘except’ => ‘getLogout’]);

      Like

    • sophia says:

      Hello There,
      If you are still looking for the answer I guess you didn’t change your Authorization sttaus from False => True
      Best of luck

      Like

    • I was able to successfully register a user with a fresh install, following the tutorial. A common error is to forget to set the private $redirectTo = ‘/’; property on the AuthController. I don’t know if that is your problem or not. If that doesn’t solve your problem, I would recommend using dd(), which is die dump to increment your way along the process and figure out where it is breaking. The trait is kind of complicated and it will be a pain, but on the other hand, you will learn a lot about the trait. Good luck.

      Like

  20. hi great tutorial but i am unfortunately stuck. I just started learning laravel 3 days ago and i seem to be making no progress at all. I simply can’t route to any page! except public, why? i copied your auth folder and all in the reources/views but it gives me a 404 not found error. I don’t understand this whole routing thing at all. The only page i can go to is the public/. Please your explanation would be highly appreciated

    Like

  21. Troels says:

    This is a great guide.
    I have implemented the master page, which works great. The problem is when i try to access the register page (or login for that matter, and any other page.) i get a 404 page not found which i don’t get. do you know what the problem might be?
    i am running laravel 5.1.19 where the file structure seems to be a bit different.
    Regards Troels

    Like

  22. Troels says:

    I have implemented the master.blad.php which works fine. my problem is that the links to the reistration and login files gives a 404 page not found. do you hav any idea what might cause this?

    im using laravel 5.1.19 which seems to have a slightly different structure than the one described in the tutorial.

    otherwise a great guide.

    Like

  23. khande1n says:

    Hi Bill, this tutorial is awesome. 🙂

    1. Now, when I try to register by filling the form, it does not show error inspite of code written for showing error on login.blade.php and register.blade.php.

    @if (count($errors) > 0)

    Whoops! There were some problems with your input.

    @foreach ($errors->all() as $error)
    {{ $error }}
    @endforeach

    @endif

    2. When I submit the form, both login and register, the page gets directed to :/home. But I have already mentioned (see below) in my AuthController.
    protected $redirectPath = ‘pages/dashboard’;
    protected $loginPath = ‘auth/login’;

    3. My Routes.php looks like:

    // Authentication routes…
    Route::get(‘auth/login’, ‘Auth\AuthController@getLogin’);
    Route::post(‘auth/login’, ‘Auth\AuthController@postLogin’);
    Route::get(‘auth/logout’, ‘Auth\AuthController@getLogout’);

    // Registration routes…
    Route::get(‘auth/register’, ‘Auth\AuthController@getRegister’);
    Route::post(‘auth/register’, ‘Auth\AuthController@postRegister’);

    Route::controllers([
    ‘password’ => ‘Auth\PasswordController’,
    ]);

    // Pages routes
    Route::get(‘/’, function () {
    return view(‘welcome’);
    });

    Route::get(‘auth/login’, function() {
    return view(‘auth/login’);
    });

    Route::get(‘auth/register’, function() {
    return view(‘auth/register’);
    });

    Route::get(‘pages/dashboard’, function() {
    return view(‘pages/dashboard’);
    });

    So, my issue is my Validator is not working (as no error when when password less than 6 character)

    Also, why it is redirecting page to /home when I have mentioned to do redirect to : pages/dashboard.

    THANK YOU!!!

    Like

    • You want to use the redirectTo property, not redirectPath for setting your redirect. I have not used loginPath property as you have, but I noticed in the trait, it is ‘/auth/login’, so you might be missing a backslash. If the validation rule is not being enforced, it would explain why you are not seeing the error. I hope that helps.

      Like

      • khande1n says:

        Hi.. Thanks for the prompt reply. I just saw one of your reply above, which mentioned to go to auth/logout as without logout we cannot register again. As this was the problem I was facing, which is solved now 🙂

        Also, for the redirectpath and Loginpath property, these have been taken from laravel 5.1 documentation.

        But thanks a lot for getting my stuff done which has only become possible because of yours detailed and clear explanation.

        Like

  24. Jessica says:

    I followed this guide, but when I try to login I get this:

    Login
    Whoops! There were some problems with your input.

    The email has already been taken.
    The password confirmation does not match.
    E-Mail Address

    Like

  25. yeffer29 says:

    It’s fair to say when something is well done and this tutorial is the best ever. Congratulations. It was very helpful. Keep working that way.

    Like

  26. Hi Bill,
    Thank you for such a nice tutorial. Everything worked very well. But when I wanted to add a new field in my registration form, it became problematic. When I try to submit my form It says,

    Whoops, looks like something went wrong.

    1/1 BadMethodCallException in Validator.php line 2638:
    Method [validateUsername] does not exist.

    Can you please help me to solve the problem???

    Like

    • Sorry, that’s beyond the scope of the tutorial. It gets complex because of the traits. You could overwrite some of the trait methods in the auth controller to account for the new attribute. You have to work your way through the trait to see how everything is being used…

      Like

  27. Victor says:

    Thanks for the great tutorial! I followed it and now have a working login system. My question is how to get the current authenticated user object from within a Controller. I found various sources online, like calling a static Auth::user(); but that doesn’t seem to work, I also don’t know what namespace the Auth class is supposed to live in. Could you help me here? Thanks!

    Like

  28. Halo, thanks for the tutorial. Iam using Laravel 5.1.24 and i follow your instruction and i got the register work by accessing localhost/laraexam/public/auth/register but when i tried to register and push the register button, it just jumped into localhost/auth/register & object not found. and i cant found the id that i just input in the database. can you help me?

    Thank you so much.

    Like

Leave a comment