Build a PHP login system using Laravel 5

Laravel makes it super easy to build a login system because it has everything already built and configured for you, here is how to create a login system using Laravel 5.2

Lets create a new Laravel project using composer:

 composer create-project --prefer-dist laravel/laravel login 

To get the authentication up and running we need to do a few things but luckily Laravel makes the set-up a breeze.

First lets set-up the database configuration. Open up the .env file in the root of your project and modify it with your database credentials.

DB_DATABASE=**Database name**
DB_USERNAME=**Database username**
DB_PASSWORD=**Database password**

Now we have that set-up we can trigger the database migration to create the tables for us:

php artisan migrate

This will now create 3 tables for us:

  • migrations
  • password_resets
  • users

The Laravel authentication system will use these tables to store the users. The migrations table is out of the scope of this tutorial but it simply remembers what migrations have been run and when.

We now need to create our routes, again Laravel makes this super simple with the artisan generator:

 php artisan make:auth 


This will create all the routes needed for a full login system. Navigate to your project URL and you will be greeted with a welcome page for your application which you can now register a new account. Create a new account and login. You should now see your protected dashboard page which is only accessible when you’re logged in.


Protecting other controllers is now super simple by calling the auth middleware in the constructor:

public function __construct(){

What if you only want to protect one or a few methods in a controller? Well that is simple as well, just pass the method name as the second parameter:

public function __construct(){
    $this->middleware('auth', ['only' => ['index']);

The above code will only apply the auth middleware to the index method in the current class, all other methods will not run the auth middleware. Laravel also allows us to do the reverse of this by applying the middleware to everything ‘except’ methods we don’t want it to run on:

public function __construct(){
    $this->middleware('auth', ['except' => ['index']);

So the above code will run the auth middleware on every method in the current class except the index method.

Leave a Reply

Your email address will not be published. Required fields are marked *