Advertisement
  1. Code
  2. Coding Fundamentals
  3. Authentication

Setting Up User Authentication in Laravel Using Confide

Scroll to top

User authentication is part of almost every web application. Although it is common, a deeper look shows that it’s not as simple as it may seem. Remember that validation, password recovery, and email confirmation are vital to any decent authentication form.

Confide is an authentication solution for Laravel made to reduce the repetitive work involving the management of users. It's a DRY approach on features like account creation, login, logout, confirmation by e-mail, password reset, etc.

Since the early versions, Confide always had good adoption among developers and a wide presence in Laravel projects. With a recent update, the package is now compatible with Laravel 4.2 which is the latest stable release of Laravel at the time of this writing.

What We Are Going to Do

In this tutorial, we’ll start from the very beginning by creating our Laravel app using Composer and then:

  • create a signup form with a full set of validation rules
  • a login form with a "forgot my password" option that will send a link for the user to redefine his password
  • use Laravel filters to only allow logged users can access a specific route.

Creating the Application

First of all, let's create the application using Composer.

1
$ composer create-project laravel/laravel myapp

Installing Confide

Now, with inside the project directory, edit the require key of composer.json file and include confide entry:

1
"require": { "laravel/framework": "~4.2", "zizaco/confide": "~4.0@dev" },

Then run composer update on our new dependency:

1
$ composer update zizaco/confide

In config/app.php of our project, add 'Zizaco\Confide\ServiceProvider' to the end of the providers array:

1
... 'providers' => array( 'Illuminate\Foundation\Providers\ArtisanServiceProvider', 'Illuminate\Auth\AuthServiceProvider', ... 'Zizaco\Confide\ServiceProvider', ), ...

Also add 'Confide' => 'Zizaco\Confide\Facade' to the aliases array in the same file:

1
... 'aliases' => array( 'App' => 'Illuminate\Support\Facades\App', 'Artisan' => 'Illuminate\Support\Facades\Artisan', ... 'Confide' => 'Zizaco\Confide\Facade', ),

Set the address and name in config/mail.php. This config will be used to send account confirmation and password reset emails to the users. For this tutorial, you can use your personal SMTP server to get things working

For example, if you use Gmail you can do the following:

1
'driver' => 'smtp', 'host' => 'smtp.gmail.com', // For testing purposes 

2
'from' => array( 'address' => 'youremail@gmail.com', 'name' => 'MyApp' ), ... 'username' => 'youremail@gmail.com', 'password' => '<password>, ...

User model

Now generate the Confide migrations by running:

1
$ php artisan confide:migration $ php artisan migrate

This will setup a table containing email, password, remember_token, confirmation_code and confirmed columns. These are the default fields needed for Confide. Feel free to add more columns to the table later.

Replace all the code in app/models/User.php to:

1
<?php 
2
use Zizaco\Confide\ConfideUser; 
3
use Zizaco\Confide\ConfideUserInterface; 
4
5
class User extends Eloquent implements ConfideUserInterface { 
6
    use ConfideUser; 
7
}

Zizaco\Confide\ConfideUser trait will take care of most behaviors of the user model.

UsersController and Routes

Confide contains a generator tool that will create a controller and write the routes for us. To create the UsersController and to register the routes let's run these commands:

1
$ php artisan confide:controller 
2
$ php artisan confide:routes

Since new classes have been created, we will need to refresh the autoload files.

1
$ composer dump-autoload

Ready to Use

We are done! Our application now has all of the features that Confide offers. Run the application server by calling php artisan serve in the terminal.

The following GET routes are available in our application:

1
http://localhost:8000/users/create 
2
http://localhost:8000/users/login 
3
http://localhost:8000/users/forgot_password

To access the current user we can call Confide::user(). Therefore, to show the name of the current user we need to replace the content of app/views/hello.php with:

1
<!doctype html>
2
<html lang="en">
3
<head>
4
    <meta charset="UTF-8">
5
    <title>User auth with Confide</title>
6
</head>
7
<body>
8
    <h1>Hello Confide</h1>
9
    <p>
10
        Hi
11
        <?php echo (Confide::user() ?: 'visitor') ?>
12
    </p>
13
</body>
14
</html>

Now go ahead and access http://localhost:8000/users/create to create our first user. You will receive a confirmation email right after submitting the form (if you have filled the config/mail.php with the correct values). Log-in and you will see the username on the screen.

Displaying the username on the page

Improving Visuals

The default forms of Confide are compatible with Bootstrap. So don't be intimidated by the "ugliness" of them on a page without any CSS. Edit the controller generated by Confide (UserController.php) and update the create method to:

1
<?php
2
3
public function create() { 
4
    return View::make('users.signup'); 
5
}

Thus our application will render the View users.signup. Let's create this view in app/views/users as signup.blade.php with the following content:

1
<!doctype html> 
2
<html lang="en"> 
3
    <head> 
4
        	<meta charset="UTF-8"> 
5
        	<title>User auth with Confide</title> 
6
        	{{-- Imports twitter bootstrap and set some styling --}} 
7
        	<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"> 
8
		<style> 
9
		body { background-color: #EEE; } 
10
		.maincontent { 
11
			background-color: #FFF; 
12
			margin: auto; 
13
			padding: 20px; 
14
			width: 300px; 
15
			box-shadow: 0 0 20px #AAA;
16
		} 
17
		</style> 
18
	</head> 
19
	<body> 
20
		<div class="maincontent"> 
21
			<h1>Signup</h1> 
22
			{{-- Renders the signup form of Confide --}}
23
			{{ Confide::makeSignupForm()->render(); }} 
24
		</div> 
25
	</body> 
26
</html>

After this, we will have a much more elegant result in the user creation form on http://localhost:8000/user/create:

Improved Signup form

You don't have to use the forms generated by Confide. You can create your own view that sends data to the POST routes.

Restricting Access

Open app/routes.php and add the code below to the bottom of the file:

1
// Dashboard route 

2
Route::get('userpanel/dashboard', function(){ return View::make('userpanel.dashboard'); }); 
3
4
// Applies auth filter to the routes within admin/ 

5
Route::when('userpanel/*', 'auth');

Create the view file app/views/userpanel/dashboard.blade.php:

1
<!doctype html>
2
<html lang="en">
3
<head>
4
    <meta charset="UTF-8">
5
    <title>User auth with Confide</title>
6
    {{-- Imports twitter bootstrap and set some styling --}}
7
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
8
    <style>
9
        body { background-color: #EEE; }
10
        .maincontent {
11
            background-color: #FFF;
12
            margin: 30px auto;
13
            padding: 20px;
14
            width: 300px;
15
            box-shadow: 0 0 20px #AAA;
16
        }
17
    </style>
18
</head>
19
<body>
20
    <div class="maincontent">
21
        <h1>{{ Confide::user()->username }}</h1>
22
        <div class="well">
23
            <b>email:</b> {{ Confide::user()->email }}
24
        </div>
25
     </div>
26
</body>
27
</html>

Now that we have applied the filter to all routes within userpanel. We will need a small tweak to ensure that the auth filter will redirect the user to the correct login URL. Edit app/filters.php on line 46 in order to replace return Redirect::guest('login'); with:

1
... return Redirect::guest('users/login'); ...

That done, the userpanel/dashboard page will only be available for users who are logged into the application. The filter will redirect guest users to the login form and then back to the dashboard once they are logged in.

Conclusion

It is possible to note that we were able to quickly set up user authentication for our app. Also, the generated controller, migration and routes can be edited to customize how we will handle each detail.

We have not focused much on the ConfideUser trait, but I believe it's important to clear things up. Once your model uses the ConfideUser trait, you don't need to worry about implementing the basic logic. At the same time, you still can overwrite the methods and customize them, if necessary.

We can say that Confide is a DRY approach to user authentication. It offers the convenience of having the functionality out-of-the-box while still allows high customization.

Check out Confide on GitHub. If you had any issue while following this tutorial, feel free to contact me.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.