Laravel 5.4 #6 : User authentication

Today we will learn how to create a login and registration form and we will see that Laravel creates it automatically with only one command. We will also see how to customize the form by adding a new field and also verify that only active users can login.

Create authentication system

Laravel is able to generate everything you need for the authentication of a project (forms, classes, routes, etc.) simply with a command and from there we can customize everything we want. So, we save a lot of time, since it is a task that in almost all the projects we would have to do.

We will see that many files have been created, including some views. One of them is a layout and what I’m going to do is to extend the views we created earlier and extend them from a layout, change it for this one. The change would be this:

Now it has everything more or less the same style, although they would need to touch up some things, since I’m not using Bootstrap classes then it looks very close to the margins. But by looking at the other views, we can adapt it easily.

 

Modify register form

To add a field to the registration form, first of all we have to create a migration so that the field is added to the database table. I, for example, have decided to put the country field, but you can put anything.

Open the file and put this:

Execute the migrations:

Now we have to add the field to the form ( resources/views/auth/register.blade.php ), so add this code aqfter the email section:

Once this is done, we have to add it to the method that check it and save it.

Finally, we have to indicate in the model that it will fill the country field:

Once we get this done, we already have everything, it will save in the database when we register and we can access it from the user object or from auth object.

 

Check if the user who is logged in is active

If we want only to be able to login active users, first of all we have to create a column that is to know if it is active or not.

Open the file and add this:

Execute it:

We already have the column in the database, now only is missing the checking that we have to put it in the controller of the login. We add the following code that will do the verification that the user is active:

Now wehe we try to log in with a inactive user, Laravel will display a error message. These checks also could be applied for other types of things.

 

In the next post, we will use the middleware to restrict the access to some page if you are not logged in and we will explain how to create a custom one.