Simple and Easy Laravel Login Authentication

Chris Sevilleja
This article has been upgraded to work with Laravel 4.1.26

Today we'll be creating a simple Laravel authentication. Using migrations, seeding, routes, controllers, and views, we'll walk through the entire process.

This tutorial will walk us through:

  • Creating a users table using migrations
  • Filling our new users table with sample users using seeding
  • Using the great artisan command line tool to migrate and seed
  • Creating a login form and processing a login using routes, controllers, and views
  • Handling login errors
  • Use Eloquent ORM to validate a user

Getting our Database Ready

To get our authentication working, we will need to have a database and users to login with.

Database Setup

Set up your database and user. Assign that user to the database and make sure you update your settings in app/config/database.php.

Migrations

Migrations are a way we can manipulate our database within our codebase. This means we don't have to get our hands dirty by doing any SQL commands or messing around inside a tool like phpmyadmin. For more information and the benefits of migrations, see the official docs.

Migrations are very easy to create. The easiest way to create a migration will be to use the great artisan command line interface created by Taylor Otwell. To create the migration, via the command line, in the root folder of your application, simply type:

php artisan migrate:make create_users_table ––create=users

This will automatically create a migrations file inside of your app/database/migrations folder. Let's take a look at the newly created file.

// app/database/migrations/####_##_##_######_create_users_table.php

<?php

use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateUsersTable extends Migration {

  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
      Schema::create('users', function(Blueprint $table)
      {
          $table->increments('id');
          $table->timestamps();
      });
  }

  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
      //
  }

}

Laravel generates the core of the migration file for you and the --create command will let the migration create the table for you. It will create a table for you with an id field and the timestamps field. This will make created_at and updated_at fields. Now we use the Schema Builder to create our users table.

// app/database/migrations/####_##_##_######_create_users_table.php

<?php

use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateUsersTable extends Migration {

  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
      Schema::create('users', function(Blueprint $table)
      {
          $table->increments('id');

          $table->string('name', 32);
          $table->string('username', 32);
          $table->string('email', 320);
          $table->string('password', 64);

                      // required for Laravel 4.1.26
                      $table->string('remember_token', 100)->nullable();
          $table->timestamps();
      });
  }

  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
      Schema::drop('users');
  }

}

Now this migration file will be responsible for creating the users table and also destroying it if needed. To run the migration and create our user table, use the command line again and run:

php artisan migrate

Just like that, the command will use the up() function and bam! We have our users table with all the columns we wanted.

Reverting Migrations: Now if you wanted to rollback migrations, we could use php artisan migrate:rollback or php artisan migrate:reset.

Now that we have our table, lets create sample users.

Seeding

Seeding is the technique of filling our database with sample data so we can test and create our applications. It really does make building applications much easier. For seeder files, we won't be using artisan. We'll make these the good old fashioned way... New file. In your app/database/seeds folder, create a file called UserTableSeeder.php.

// app/database/seeds/UserTableSeeder.php

<?php

class UserTableSeeder extends Seeder
{

public function run()
{
    DB::table('users')->delete();
    User::create(array(
        'name'     => 'Chris Sevilleja',
        'username' => 'sevilayha',
        'email'    => 'chris@scotch.io',
        'password' => Hash::make('awesome'),
    ));
}

}

We will create a user and all of the above is pretty self explanatory aside from password. We will use Laravel's Hash class to create a secure Bcrypt hashing of our password. This is always a good practice to hash our password and to read more about Laravel security, check out the docs. Now that we have created our file, we need to Laravel to call it. Inside the app/database/seeds/DatabaseSeeder.php, add the line $this->call('UserTableSeeder');.

// app/database/seeds/DatabaseSeeder.php

<?php

class DatabaseSeeder extends Seeder {

  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run()
  {
      Eloquent::unguard();

      $this->call('UserTableSeeder');
  }

}

Once we're done with our seeder file, we can inject that user into our database using:

php artisan db:seed

The Application

Now that we have a database, a table thanks to migrations, and a user thanks to seeding, we can build the authentication system. We will need to create routes, controllers, and views for our form.

Routes

In Laravel, our routes file dictates the lay of the land in our application. We will define 2 routes for our login, one for the http get to show the form, and one for the http post request to process the form. Laravel let's us define routes based on HTTP request types and this helps to organize our application and how a user interacts around the site. For more info on this: show link. Add the following routes we need in our app/routes.php file:

// app/routes.php

<?php

// route to show the login form
Route::get('login', array('uses' => 'HomeController@showLogin'));

// route to process the form
Route::post('login', array('uses' => 'HomeController@doLogin'));

Now if we go to our application in our browser and go to www.example.com/login, we will get an error because we haven't defined the HomeController@showLogin function yet. Let's do that.

Controller

In our app/controllers directory, Laravel should already come with a HomeController.php and a BaseController.php. Inside our HomeController.php, we are going to create the two functions we need. Add these two.

// app/controllers/HomeController.php<

...

public function showLogin()
{
    // show the form
    return View::make('login');
}

public function doLogin()
{
// process the form
}

For now, we will only deal with the function to show the form.

View

The easiest part of this process will be creating our login view. In the app/views folder, create a file called login.blade.php. The .blade.php extension lets Laravel know that we will be using its Blade Templating system.

<!-- app/views/login.blade.php --><

<!doctype html>
<html>
<head>
<title>Look at me Login</title>
</head>
<body><

{{ Form::open(array('url' => 'login')) }}
<h1>Login</h1>

<!-- if there are login errors, show them here -->
<p>
    {{ $errors->first('email') }}
    {{ $errors->first('password') }}
</p>

<p>
    {{ Form::label('email', 'Email Address') }}
    {{ Form::text('email', Input::old('email'), array('placeholder' => 'awesome@awesome.com')) }}
</p>

<p>
    {{ Form::label('password', 'Password') }}
    {{ Form::password('password') }}
</p>

<p>{{ Form::submit('Submit!') }}</p>
{{ Form::close() }}

Chris Sevilleja

Co-founder of Scotch.io. Slapping the keyboard until something good happens.