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.
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.
APP_ENV=local APP_DEBUG=true APP_KEY=8wfDvMTvfXWHuYE483uXF11fvX8Qi8gC DB_HOST=localhost DB_DATABASE=laravel_5_authentication DB_USERNAME=root DB_PASSWORD=root CACHE_DRIVER=file 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.
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AlterUsersTableRemoveNameAddFirstNameLastName extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function($table){ $table->dropColumn('name'); $table->string('first_name', 50)->after('id'); $table->string('last_name', 50)->after('first_name'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function($table){ $table->dropColumn('last_name'); $table->dropColumn('first_name'); $table->string('name')->after('id'); }); } }
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
.
<?php namespace App\Services; use App\User; use Validator; use Illuminate\Contracts\Auth\Registrar as RegistrarContract; class Registrar implements RegistrarContract { /** * Get a validator for an incoming registration request. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ public function validator(array $data) { return Validator::make($data, [ 'first_name' => 'required|min:3|max:50', 'last_name' => 'required|min:3|max:50', 'email' => 'required|email|max:255|unique:users', 'password' => 'required|confirmed|min:6', ]); } /** * Create a new user instance after a valid registration. * * @param array $data * @return User */ public function create(array $data) { return User::create([ 'first_name' => $data['first_name'], 'last_name' => $data['last_name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), ]); } }
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
.
<?php namespace App; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; class User extends Model implements AuthenticatableContract, CanResetPasswordContract { use Authenticatable, CanResetPassword; /** * The database table used by the model. * * @var string */ protected $table = 'users'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = ['first_name', 'last_name', 'email', 'password']; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = ['password', 'remember_token']; }
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
.
@extends('app') @section('content') <div class="container-fluid"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading">Register</div> <div class="panel-body"> @if (count($errors) > 0) <div class="alert alert-danger"> <strong>Whoops!</strong> There were some problems with your input.<br><br> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <form class="form-horizontal" role="form" method="POST" action="/auth/register"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> <div class="form-group"> <label class="col-md-4 control-label">First Name</label> <div class="col-md-6"> <input type="text" class="form-control" name="first_name" value="{{ old('first_name') }}"> </div> </div> <div class="form-group"> <label class="col-md-4 control-label">Last Name</label> <div class="col-md-6"> <input type="text" class="form-control" name="last_name" value="{{ old('last_name') }}"> </div> </div> <div class="form-group"> <label class="col-md-4 control-label">E-Mail Address</label> <div class="col-md-6"> <input type="email" class="form-control" name="email" value="{{ old('email') }}"> </div> </div> <div class="form-group"> <label class="col-md-4 control-label">Password</label> <div class="col-md-6"> <input type="password" class="form-control" name="password"> </div> </div> <div class="form-group"> <label class="col-md-4 control-label">Confirm Password</label> <div class="col-md-6"> <input type="password" class="form-control" name="password_confirmation"> </div> </div> <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <button type="submit" class="btn btn-primary"> Register </button> </div> </div> </form> </div> </div> </div> </div> </div> @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.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Laravel 5: Using The Authentication Facade</title> <link href="/css/bootstrap.min.css" rel="stylesheet"> <link href="/css/bootstrap-theme.min.css" rel="stylesheet"> <link href="/css/app.css" rel="stylesheet"> <!-- Fonts --> <!--<link href='//fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>--> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle Navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Laravel</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li><a href="/">Home</a></li> </ul> <ul class="nav navbar-nav navbar-right"> @if (Auth::guest()) <li><a href="/auth/login">Login</a></li> <li><a href="/auth/register">Register</a></li> @else <li class="dropdown"> <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> <ul class="dropdown-menu" role="menu"> <li><a href="/auth/logout">Logout</a></li> </ul> </li> @endif </ul> </div> </div> </nav> <div class="container"> @yield('content') </div> <!-- Scripts --> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script> </body> </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.
// route closure Route::get('<your-route-uri>', ['middleware' => 'auth', function() { // if user is not logged in // he/she will be redirected to the login page // and this code will not be executed }]); // controller action Route::get('<your-route-uri>', ['middleware' => 'auth', 'uses' => '<your-controller>@<your-action>']); // within a controller class YourController extends Controller { public function __construct() { $this->middleware('<your-middleware-name>'); $this->middleware('<another-middleware>', ['only' => ['<some-action-name>']]); $this->middleware('<more-middleware>', ['except' => ['<another-action-name>']]); } }
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
.
// Example 1 // login url http://www.example.com/account/login // logout url http://www.example.com/account/logout // registration url http://www.example.com/account/register Route::controllers([ 'account' => 'Auth\AuthController', 'password' => 'Auth\PasswordController', ]); // Example 2 // login url http://www.example.com/login // logout url http://www.example.com/logout // registration url http://www.example.com/register Route::controllers([ '' => 'Auth\AuthController', 'password' => 'Auth\PasswordController', ]); // Example 3 // redefine all routes Route::get('example/register', 'Auth\AuthController@getRegister'); Route::post('example/register', 'Auth\AuthController@postRegister'); Route::get('example/login', 'Auth\AuthController@getLogin'); Route::post('example/login', 'Auth\AuthController@postLogin'); Route::get('example/logout', 'Auth\AuthController@getLogout'); Route::get('example/email', 'Auth\PasswordController@getEmail'); Route::post('example/email', 'Auth\PasswordController@postEmail'); Route::get('example/reset/{code}', 'Auth\PasswordController@getReset'); 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!
By the way, if you need extra help with fixing bugs or making customizations you're not comfortable with, contact one of the PHP service providers on Envato Studio. They can help you with a wide range of problems quickly and reliably, so that with a small investment of money, you can save yourself a whole lot of time!
Comments