1. Code
  2. Coding Fundamentals
  3. Authentication

Using Laravel 5's Authentication Facade

Scroll to top

Authentication is a part of almost all the web applications you work with. It's really boring to keep repeating all the boilerplate code in every project. Well, the good news is Laravel 5 rids you of this boredom by providing a ready-to-use authentication facade. 

All you need to do is configure and customize the authentication service provider to your project's needs. In this quick tip, I am going to show you exactly how to do that.

Looking for a Shortcut?

If you want a ready-made, tried and tested solution, try Vanguard - Advanced PHP Login and User Management on Envato Market. It's a PHP application, written in Laravel 5.2, that allows website owners to quickly add and enable authentication, authorisation and user management on their website. 

Vanguard - Advanced PHP Login and User Management on Envato MarketVanguard - Advanced PHP Login and User Management on Envato MarketVanguard - Advanced PHP Login and User Management on Envato Market
Vanguard - Advanced PHP Login and User Management on Envato Market

Setting Up the Environment

I am going to assume you are starting off with a fresh Laravel 5 installation, but you can skip any of these steps if you have already done them. First off, you are going to set some environment variables in the .env file at the root of your project. Basically, these have to do with the database configuration.

1
APP_ENV=local
2
APP_DEBUG=true
3
APP_KEY=8wfDvMTvfXWHuYE483uXF11fvX8Qi8gC
4
5
DB_HOST=localhost
6
DB_DATABASE=laravel_5_authentication
7
DB_USERNAME=root
8
DB_PASSWORD=root
9
10
CACHE_DRIVER=file
11
SESSION_DRIVER=file

Notice the APP_ENV,  DB_HOST,  DB_DATABASE,  DB_USERNAME, and  DB_PASSWORD variables. The APP_ENV variable tells Laravel which environment we wish to run our web application in. The rest of the database variable names are pretty obvious. 

This is all you need to do to configure the database connection. But how does Laravel make use of these variables? Let's examine the config/database.php file. You will notice the use of the env() function. For example, env('DB_HOST', 'localhost'). Laravel 5 uses this function to capture variables from the $_ENV and $_SERVER global arrays, which are automatically populated with the variables you define in the .env file.

Setting Up the Migrations

Execute php artisan migrate:install --env=local in your terminal at the root of your project to install the migrations locally. Also notice that there are two migrations already defined in the database/migrations folder. Using these migrations, Laravel 5 creates a users and a password_resets table, allowing the default authentication boilerplate to work. I am going to create a third migration to modify the users table just to show you how to customize the default authentication setup.

Execute php artisan make:migration alter_users_table_remove_name_add_first_name_last_name in the terminal to create a third migration.

1
<?php
2
3
use Illuminate\Database\Schema\Blueprint;
4
use Illuminate\Database\Migrations\Migration;
5
6
class AlterUsersTableRemoveNameAddFirstNameLastName extends Migration {
7
8
    /**

9
	 * Run the migrations.

10
	 *

11
	 * @return void

12
	 */
13
	public function up()
14
	{
15
		Schema::table('users', function($table){
16
			$table->dropColumn('name');
17
			$table->string('first_name', 50)->after('id');
18
			$table->string('last_name', 50)->after('first_name');
19
		});
20
	}
21
22
	/**

23
	 * Reverse the migrations.

24
	 *

25
	 * @return void

26
	 */
27
	public function down()
28
	{
29
		Schema::table('users', function($table){
30
			$table->dropColumn('last_name');
31
			$table->dropColumn('first_name');
32
			$table->string('name')->after('id');
33
		});
34
	}
35
36
}

As you can see, you have removed the name field and added two more fields for first_name and last_name with a maximum length of 50 characters. You have also added the code that rolls back these changes in the database.

Execute php artisan migrate in the terminal. If the migrations ran successfully, you should be able to see both the tables in your database with the fields you defined.

Configuring the Registrar Service

You are going to configure the Registrar service to add your newly defined users table fields. 

Edit the file app/Services/Registrar.php.

1
<?php namespace App\Services;
2
3
use App\User;
4
use Validator;
5
use Illuminate\Contracts\Auth\Registrar as RegistrarContract;
6
7
class Registrar implements RegistrarContract {
8
9
    /**

10
	 * Get a validator for an incoming registration request.

11
	 *

12
	 * @param  array  $data

13
	 * @return \Illuminate\Contracts\Validation\Validator

14
	 */
15
	public function validator(array $data)
16
	{
17
		return Validator::make($data, [
18
			'first_name' => 'required|min:3|max:50',
19
			'last_name' => 'required|min:3|max:50',
20
			'email' => 'required|email|max:255|unique:users',
21
			'password' => 'required|confirmed|min:6',
22
		]);
23
	}
24
25
	/**

26
	 * Create a new user instance after a valid registration.

27
	 *

28
	 * @param  array  $data

29
	 * @return User

30
	 */
31
	public function create(array $data)
32
	{
33
		return User::create([
34
			'first_name' => $data['first_name'],
35
			'last_name' => $data['last_name'],
36
			'email' => $data['email'],
37
			'password' => bcrypt($data['password']),
38
		]);
39
	}
40
41
}

The validator function validates the data passed in from the user registration form. You have removed the default name field and added the first_name and last_name fields with a minimum length of three characters and a maximum length of 50 characters for both. The create function adds the registered user to the users table in the database, so you only need to include the first_name and last_name fields to it.

Updating the User Model

You will also need to update the User model to include the first_name and last_name fields. 

Edit the file app/User.php.

1
<?php namespace App;
2
3
use Illuminate\Auth\Authenticatable;
4
use Illuminate\Database\Eloquent\Model;
5
use Illuminate\Auth\Passwords\CanResetPassword;
6
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
7
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
8
9
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
10
11
    use Authenticatable, CanResetPassword;
12
13
	/**

14
	 * The database table used by the model.

15
	 *

16
	 * @var string

17
	 */
18
	protected $table = 'users';
19
20
	/**

21
	 * The attributes that are mass assignable.

22
	 *

23
	 * @var array

24
	 */
25
	protected $fillable = ['first_name', 'last_name', 'email', 'password'];
26
27
	/**

28
	 * The attributes excluded from the model's JSON form.

29
	 *

30
	 * @var array

31
	 */
32
	protected $hidden = ['password', 'remember_token'];
33
34
}

The $fillable array specifies which fields of the model are open to modification. You would generally not include fields that are auto-generated into this array or fields that do not require a user's input like the hash for a remember me token. All you have done is update the $fillable array to allow the first_name and last_name to be mass assignable.

Updating the View

Finally, you just need to update the front-end views to include the first_name and last_name fields. First, you will update the registration form. 

Edit the file resources/views/auth/register.blade.php.

1
@extends('app')
2
3
@section('content')
4
5
<div class="container-fluid">
6
    <div class="row">
7
		<div class="col-md-8 col-md-offset-2">
8
			<div class="panel panel-default">
9
				<div class="panel-heading">Register</div>
10
				<div class="panel-body">
11
					@if (count($errors) > 0)
12
						<div class="alert alert-danger">
13
							<strong>Whoops!</strong> There were some problems with your input.<br><br>
14
							<ul>
15
								@foreach ($errors->all() as $error)
16
									<li>{{ $error }}</li>
17
								@endforeach
18
							</ul>
19
						</div>
20
					@endif
21
22
					<form class="form-horizontal" role="form" method="POST" action="/auth/register">
23
						<input type="hidden" name="_token" value="{{ csrf_token() }}">
24
25
						<div class="form-group">
26
							<label class="col-md-4 control-label">First Name</label>
27
							<div class="col-md-6">
28
								<input type="text" class="form-control" name="first_name" value="{{ old('first_name') }}">
29
							</div>
30
						</div>
31
32
						<div class="form-group">
33
							<label class="col-md-4 control-label">Last Name</label>
34
							<div class="col-md-6">
35
								<input type="text" class="form-control" name="last_name" value="{{ old('last_name') }}">
36
							</div>
37
						</div>
38
39
						<div class="form-group">
40
							<label class="col-md-4 control-label">E-Mail Address</label>
41
							<div class="col-md-6">
42
								<input type="email" class="form-control" name="email" value="{{ old('email') }}">
43
							</div>
44
						</div>
45
46
						<div class="form-group">
47
							<label class="col-md-4 control-label">Password</label>
48
							<div class="col-md-6">
49
								<input type="password" class="form-control" name="password">
50
							</div>
51
						</div>
52
53
						<div class="form-group">
54
							<label class="col-md-4 control-label">Confirm Password</label>
55
							<div class="col-md-6">
56
								<input type="password" class="form-control" name="password_confirmation">
57
							</div>
58
						</div>
59
60
						<div class="form-group">
61
							<div class="col-md-6 col-md-offset-4">
62
								<button type="submit" class="btn btn-primary">
63
									Register
64
								</button>
65
							</div>
66
						</div>
67
					</form>
68
				</div>
69
			</div>
70
		</div>
71
	</div>
72
</div>
73
74
@endsection

You have added the first_name and last_name fields to the registration form. You also need to edit the default app layout at resources/views/app.blade.php to show the logged-in user's name in the navigation menu.

1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
    <meta charset="utf-8">
5
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
6
	<meta name="viewport" content="width=device-width, initial-scale=1">
7
	<title>Laravel 5: Using The Authentication Facade</title>
8
9
	<link href="/css/bootstrap.min.css" rel="stylesheet">
10
	<link href="/css/bootstrap-theme.min.css" rel="stylesheet">
11
	<link href="/css/app.css" rel="stylesheet">
12
13
	<!-- Fonts -->
14
	<!--<link href='//fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>-->
15
16
	<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
17
	<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
18
	<!--[if lt IE 9]>

19
		<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>

20
		<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>

21
	<![endif]-->
22
</head>
23
<body>
24
	<nav class="navbar navbar-default">
25
		<div class="container-fluid">
26
			<div class="navbar-header">
27
				<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
28
					<span class="sr-only">Toggle Navigation</span>
29
					<span class="icon-bar"></span>
30
					<span class="icon-bar"></span>
31
					<span class="icon-bar"></span>
32
				</button>
33
				<a class="navbar-brand" href="#">Laravel</a>
34
			</div>
35
36
			<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
37
				<ul class="nav navbar-nav">
38
					<li><a href="/">Home</a></li>
39
				</ul>
40
41
				<ul class="nav navbar-nav navbar-right">
42
					@if (Auth::guest())
43
						<li><a href="/auth/login">Login</a></li>
44
						<li><a href="/auth/register">Register</a></li>
45
					@else
46
						<li class="dropdown">
47
							<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">{{ Auth::user()->first_name . ' ' . Auth::user()->last_name }} <span class="caret"></span></a>
48
							<ul class="dropdown-menu" role="menu">
49
								<li><a href="/auth/logout">Logout</a></li>
50
							</ul>
51
						</li>
52
					@endif
53
				</ul>
54
			</div>
55
		</div>
56
	</nav>
57
58
	<div class="container">
59
		@yield('content')
60
	</div>
61
62
	<!-- Scripts -->
63
	<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
64
	<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
65
</body>
66
</html>

Securing Your Routes

To secure your routes and allow only logged-in users to be able to access them, you need to make use of the auth middleware which is provided by Laravel. The auth middleware can be found at app\Http\Middleware\Authenticate.php

Here are a few examples of how to use it to protect your routes.

1
// route closure

2
Route::get('<your-route-uri>', ['middleware' => 'auth', function()
3
{
4
    // if user is not logged in

5
    // he/she will be redirected to the login page

6
    // and this code will not be executed

7
}]);
8
9
// controller action

10
Route::get('<your-route-uri>', ['middleware' => 'auth', 'uses' => '<your-controller>@<your-action>']);
11
12
// within a controller

13
class YourController extends Controller {
14
15
    public function __construct()
16
    {
17
        $this->middleware('<your-middleware-name>');
18
19
        $this->middleware('<another-middleware>', ['only' => ['<some-action-name>']]);
20
21
        $this->middleware('<more-middleware>', ['except' => ['<another-action-name>']]);
22
    }
23
24
}

Modifying the Default Authentication Routes

You can execute php artisan route:list in the terminal to check the default routes the authentication facade uses. You can access these routes to test your authentication code. Here are a few examples of how to modify these routes.

Edit the file app/Http/routes.php.

1
// Example 1

2
// login url https://www.example.com/account/login

3
// logout url http://www.example.com/account/logout

4
// registration url http://www.example.com/account/register

5
Route::controllers([
6
    'account' => 'Auth\AuthController',
7
    'password' => 'Auth\PasswordController',
8
]);
9
10
// Example 2

11
// login url http://www.example.com/login

12
// logout url http://www.example.com/logout

13
// registration url http://www.example.com/register

14
Route::controllers([
15
	'' => 'Auth\AuthController', 
16
	'password' => 'Auth\PasswordController',
17
]);
18
19
// Example 3

20
// redefine all routes

21
Route::get('example/register', 'Auth\AuthController@getRegister');
22
Route::post('example/register', 'Auth\AuthController@postRegister');
23
Route::get('example/login', 'Auth\AuthController@getLogin');
24
Route::post('example/login', 'Auth\AuthController@postLogin');
25
Route::get('example/logout', 'Auth\AuthController@getLogout');
26
Route::get('example/email', 'Auth\PasswordController@getEmail');
27
Route::post('example/email', 'Auth\PasswordController@postEmail');
28
Route::get('example/reset/{code}', 'Auth\PasswordController@getReset');
29
Route::post('example/reset', 'Auth\PasswordController@postReset');

Also, remember to call the URIs dynamically in your views and email templates using the Laravel helpers. You can see how to do that in the GitHub repository of this quick tip.

Final Thoughts

The password reset feature sends the password reset link to the user's email, so make sure you have the mail configuration set up in your Laravel project. The view template for the password reset email is at resources/views/emails/password.blade.php. You can also configure a few other basic options in the config/auth.php file.

I hope you found this quick tip easy to follow. Until my next Tuts+ piece, happy coding!

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.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.