User Authentication in Laravel 4.x: Simple Guide Part 1

user authentication in laravel 4 part 1

User Authentication In Laravel 4 Tutorial

In my previous article regarding Laravel migrations, I have mentioned that Laravel has a nice Authentication component. Today, we will see how we can use Laravel’s Auth component to build a simple user authentication in Laravel 4. So, let’s get started.

user authentication in laravel 4 part 1

User Authentication in Laravel 4 Screenshot

You can install Laravel by following the instructions provided on the documentation page here.

Database Creation And Configuration

First of all, we will create a database, which will be used by our Laravel authentication application. I will be using the MySQL terminal client for this purpose.

┌─[usm4n@usm4n-desktop]―[~]
└─•mysql -u root -p
Enter password: 
mysql> create database laravel;
Query OK, 1 row affected (0.00 sec)

In the above bash snippet, I have created a database with a name laravel, Now its time to configure database connection in /app/config/database.php like this:

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'laravel',
    'username'  => 'root',
    'password'  => 'very_secret_password',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

After making the above changes in mysql array save the file and we are done.

Creating Migrations

Laravel already provides us with a User model, and Auth component comes preconfigured to use this model. We just need a users table to make it all work. So, let us create a migration for users table. (see my previous article on Laravel Migrations)

┌─[usm4n@usm4n-desktop]―[~]
└─•artisan migrate:make create_users_table --table='users'
Created Migration: 2013_12_13_140249_create_users_table
Generating optimized class loader

Now, let us edit our migration file 2013_12_13_140249_create_users_table and add columns for the users table:

<?php
//file: app/database/migrations/2013_12_13_140249_create_users_table.php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration {

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

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

}

After making above changes, we are ready to run migrations:

┌─[usm4n@usm4n-desktop]―[~]
└─•artisan migrate
Migration table created successfully.
Migrated: 2013_12_13_140249_create_users_table

Running the above command will create the users table with following schema:

user authentication in laravel 4 part 1

User Authentication In Laravel Screenshot

Seeding Users Table

Laravel seeding provides an easy way to fill database tables with test data. We use artisan db:seed command for this purpose. When we run db:seed, it calls the run method of DatabaseSeeder class by default. Let’s see how we use DatabaseSeeder class to seed users table:

<?php
//file: app/database/seeds/DatabaseSeeder.php
class DatabaseSeeder extends Seeder {

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Eloquent::unguard();
        $this->call('UserTableSeeder');
    }

}

//file: app/database/seeds/UserTableSeeder.php
<?php

class UserTableSeeder extends Seeder {

    public function run()
    {
        // Uncomment the below to wipe the table clean before populating
        // DB::table('user')->truncate();

        $user = array(
            'username' => 'usm4n',
            'password' => Hash::make('admin'),
            'created_at' => DB::raw('NOW()'),
            'updated_at' => DB::raw('NOW()'), 
            );

        // Uncomment the below to run the seeder
         DB::table('users')->insert($user);
    }

}

Now, its time to run artisan db:seed:

┌─[usm4n@usm4n-desktop]―[~]
└─•artisan db:seed
Database seeded!

Here is a screenshot of seeded users table:

user authentication in laravel 4 part 1

User Authentication In Laravel Screenshot

Since our ground work is done, its time to start building the application.

Creating Controllers

user authentication in laravel 4 part 1

/app/controller Directory Screenshot

As you can see from the above screenshot, we have two controllers: IndexController and AdminController. We will use the IndexController to display our application’s home page and give the user an opportunity to login. AdminController on the other hand, will be used to authenticate a user, and displaying dashboard page upon successful authentication.

Code for IndexController:

<?php

class IndexController extends BaseController {

    /**
     * shows index page
     * @return void
     */
    public function getIndex() 
    {
        $this->layout->content = View::make('index');
    }
}

:( I know there is nothing special about it. Let’s move on to AdminController:

<?php namespace Admin;

use BaseController;
use View;
use Redirect;
use Auth;
use Input;
use Validator;

class AdminController extends BaseController {

    public function __construct(){
        $this->beforeFilter(function(){
            if(Auth::guest()) 
                return Redirect::to('admin/login');
        },['except' => ['getLogin','postLogin']]);
    }

    public function getDashBoard()
    {
        $this->layout->content = View::make('admin.dashboard');
    }

    public function getLogin() 
    {
        $this->layout->content = View::make('admin.login');
    }

    public function postLogin()
    {
        $credentials = [
        'username'=>Input::get('username'),
        'password'=>Input::get('password')
        ];
        $rules = [
        'username' => 'required',
        'password'=>'required'
        ];
        $validator = Validator::make($credentials,$rules);
        if($validator->passes())
        {
            if(Auth::attempt($credentials))
                return Redirect::to('admin/dash-board');
            return Redirect::back()->withInput()->with('failure','username or password is invalid!');
        }
        else
        {
            return Redirect::back()->withErrors($validator)->withInput();

        }
    }

    public function getLogout()
    {
        Auth::logout();
        return Redirect::to('/');
    }

}

Since AdminController resides inside Admin directory, using namespace Admin at first line will allow the autoloader to discover its presence inside Admin directory. Next we are referencing some Laravel’s components in global namespace.

beforFilter controller method allows us to intercept calls to controller’s actions. It takes two arguments: name of the filter or a closure and an array of actions.

In AdminController's constructor, we are passing a closure as a first argument to beforeFilter. The second argument passed is an array of controller actions we don’t want to be protected by the filter. In closure, we are calling Auth::guest() function to check if a user is not logged in. In this case, a user will be redirected to the login page.

Next comes the postLogin, after checking input against some simple validation rules, we try to log in a user by calling Auth::attempt(). This method will return true if a login attempt is successful. In this case, a user will be redirected to dash-board page. If a login attempt fails, a user will be redirected back with a failure message.

The last method getLogout simply logs out a user by calling Auth::logout().

Creating Views And Routes

We will cover the views and routes in next part of this tutorial. Till then, take care :).


Leave a Reply

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


3 + three =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>