Laravel 5 Authentication

Download: Laravel Authentication

Introduction

One of the advantages of Laravel is that it comes with authentication built in into the framework. It is very easy to use. In this tutorial, we will implement authentication for the Larashop checkout page. We want to ensure that only logged in users can check out.

Topics to be covered.

We will cover the following topics in this tutorial

  • Laravel 5 authentication configurations
  • Laravel 5 basic authentication
  • How to change the default login URL
  • Laravel 5 custom authentication

Laravel 5 authentication configurations

The authentication configuration file is located in /config/auth.php The configuration file specifies the;

  1. model name
  2. users table
  3. password reset options By default, a model for users in included in /app/User.php. Open /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 = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];
}

HERE,

  • class User extends Model implements AuthenticatableContract, CanResetPasswordContract defines the User model. The user model extends Eloquent ORM model and implements two interfaces; AuthenticatableContract and CanResetPasswordContract.
  • protected $table = 'users'; explicitly sets the table name of the users
  • protected $fillable = ['name', 'email', 'password']; specifies attributes that can be mass assigned. If your table contains other database fields that you would like to manipulate via the User model, then you can specify them here.
  • protected $hidden = ['password', 'remember_token']; sets hidden fields that should be excluded from the JSON form.

Users Table Migration

By default, Laravel comes with a migration for the users table. Read the tutorial on migrations for more details if you are not familiar with the concept of migrations. open /database/migrations/ 20141012000000createuserstable.php. Note: the timestamp before the migration may be different depending on your version.

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

HERE,

  • public function up() creates the user table with the following fields
    • id autoincrement defines a primary key
    • name varchar(255) field
    • email varchar(255) field with unique attribute set to true
    • password varchar(60) field
    • rememberToken field varchar(100)
    • timestamps created two timestamp fields createdat and updatedat

If you have been following along the tutorial series, you do not need to run the migration. We already did this in the tutorial on Migrations. If you haven’t, run the following command

php artisan migrate:install

HERE,

• The above command creates the migration table. The assumption made here is that you have MySQL database configured to work with your project.

Run the following command to execute the migration

php artisan migrate

HERE,

  • The above code creates the users table in your database.

Users’ registration and login forms

The login page has two forms. One for logging in and the other for registration.

  1. Open /resources/views/login.blade.php
  2. Modify the code to the following
@extends('layouts.layout')

@section('content')       
       <section id="form"><!--form-->
            <div class="container">
                <div class="row">
                    <div class="col-sm-4 col-sm-offset-1">
                        <div class="login-form"><!--login form-->
                            <h2>Login to your account</h2>
                            <form method="POST" action="{{url('auth/login')}}">
                                {!! csrf_field() !!}
                                <input type="email" name="email" id="email" placeholder="Email Address" />
                                <input type="password" name="password" id="password" placeholder="Password" />
                                <span>
                                    <input name="remember" id="remember" type="checkbox" class="checkbox"> 
                                    Keep me signed in
                                </span>
                                <button type="submit" class="btn btn-default">Login</button>
                            </form>
                        </div><!--/login form-->
                    </div>
                    <div class="col-sm-1">
                        <h2 class="or">OR</h2>
                    </div>
                    <div class="col-sm-4">
                        <div class="signup-form"><!--sign up form-->
                            <h2>New User Signup!</h2>
                            <form method="POST" action="{{url('register')}}">
                                {!! csrf_field() !!}
                                <input type="text" name="name" id="name"  placeholder="Name">
                                <input type="email" name="email" placeholder="Email Address"/>
                                <input type="password" name="password" placeholder="Password">
                                <button type="submit" class="btn btn-default">Signup</button>
                            </form>
                        </div><!--/sign up form-->
                    </div>
                </div>
            </div>
        </section><!--/form-->
@endsection

HERE,

  • <form method="POST" action="{{url('auth/login')}}"> defines the URL for the form action. In this case, the form will be submitted to http://localhost/larashop/public/auth/login
  • <form method="POST" action="{{url('register')}}"> defines the URL for user registration.
  • {!! csrf_field() !!} adds a security hidden field token to the form.

Login, logout, and register routes

We will now add routes that will handle the authentication

  1. Open /app/Http/routes.php
  2. Add the following routes
// Authentication routes...
Route::get('auth/login', 'Front@login');
Route::post('auth/login', 'Front@authenticate');
Route::get('auth/logout', 'Front@logout');

// Registration routes...
Route::post('/register', 'Front@register');

HERE,

  • Route::get('auth/login', 'Front@login'); defines the route that displays the login and register forms
  • Route::post('auth/login', 'Front@authenticate'); defines the HTTP POST verb route that does the actual user authentication
  • Route::get('auth/logout', 'Front@logout'); defines the route that logs out a user
  • Route::post('/register', 'Front@register'); defines the HTTP POST verb route that registers users.

Protected routes

A protected route requires a user to be logged in before they can access it. This section protects the checkout URL. We want only registered users to be able to check out. The following code adds a middleware function to our route.

Route::get('/checkout', [
    'middleware' => 'auth',
    'uses' => 'Front@checkout'
]);

HERE,

  • 'middleware' => 'auth', is executed before the checkout method. auth will check if a user is logged in. If the user is not logged in, they will be redirected to /auth/login page. If the user is logged in, they will see the checkout page.

Authentication and registration route methods

We will now modify/add methods that will respond to the above routes

  1. Open /app/Http/Controllers/Front.php
  2. Modify/add the following methods

Let’s start by importing the required namespaces


use App\User;
use Illuminate\Support\Facades\Auth;

HERE,

  • use App\User; imports the User model namespace
  • use Illuminate\Support\Facades\Auth; imports the Auth namespace

Register user

public function register() {
    if (Request::isMethod('post')) {
        User::create([
                    'name' => Request::get('name'),
                    'email' => Request::get('email'),
                    'password' => bcrypt(Request::get('password')),
        ]);
    } 
    
    return Redirect::away('login');
}

HERE,

  • User::create(['name' => Request::get('name'), 'email' => Request::get('email'), 'password' => bcrypt(Request::get('password')),]); creates a user record using the supplied form user input.
  • return Redirect::away('login'); redirects the user to the login page after creating the user record.

Authenticating Users

The following method authenticates users

public function authenticate() {
    if (Auth::attempt(['email' => Request::get('email'), 'password' => Request::get('password')])) {
        return redirect()->intended('checkout');
    } else {
        return view('login', array('title' => 'Welcome', 'description' => '', 'page' => 'home'));
    }
}

HERE,

  • if (Auth::attempt(['email' => Request::get('email'), 'password' => Request::get('password')])) attempt method tries to login the user using the supplied email address and password. It returns true if the authentication is successful.
  • return redirect()->intended('checkout'); redirects the logged in user to a protected page

Logging out users

The following method logs out users

public function logout() {
    Auth::logout();
    
    return Redirect::away('login');
}

HERE,

  • Auth::logout(); calls the logout method

Displaying login information in views

We need to make one more change before we test our user registration and authentication. The following image shows the account navigation menu before login

Use composer here

When a user logins in successfully, we want to display the following information

Use composer here

We will show the registered name and change the Login link to Logout 1. open /resources/views/layouts/layout.blade.php 2. Modify the header section as follows

<header id="header"><!--header-->
        <div class="header_top"><!--header_top-->
            <div class="container">
                <div class="row">
                    <div class="col-sm-6">
                        <div class="contactinfo">
                            <ul class="nav nav-pills">
                                <li><a href="#"><i class="fa fa-phone"></i> +2 95 01 88 821</a></li>
                                <li><a href="#"><i class="fa fa-envelope"></i> info@domain.com</a></li>
                            </ul>
                        </div>
                    </div>
                    <div class="col-sm-6">
                        <div class="social-icons pull-right">
                            <ul class="nav navbar-nav">
                                <li><a href="#"><i class="fa fa-facebook"></i></a></li>
                                <li><a href="#"><i class="fa fa-twitter"></i></a></li>
                                <li><a href="#"><i class="fa fa-linkedin"></i></a></li>
                                <li><a href="#"><i class="fa fa-dribbble"></i></a></li>
                                <li><a href="#"><i class="fa fa-google-plus"></i></a></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div><!--/header_top-->

        <div class="header-middle"><!--header-middle-->
            <div class="container">
                <div class="row">
                    <div class="col-sm-4">
                        <div class="logo pull-left">
                            <a href="{{url('')}}"><img src="{{asset('images/home/logo.png')}}" alt="" /></a>
                        </div>
                    </div>
                    <div class="col-sm-8">
                        <div class="shop-menu pull-right">
                            <ul class="nav navbar-nav">
                                <li><a href="#"><i class="fa fa-user"></i> {{Auth::check() ? Auth::user()->name : 'Account'}}</a></li>
                                <li><a href="{{url('checkout')}}"><i class="fa fa-crosshairs"></i> Checkout</a></li>
                                <li><a href="{{url('cart')}}"><i class="fa fa-shopping-cart"></i> Cart</a></li>
                                <li><a href="{{Auth::check() ? url('auth/logout') : url('auth/login')}}"><i class="fa fa-lock"></i> {{Auth::check() ? 'Logout' : 'Login'}}</a></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div><!--/header-middle-->

        <div class="header-bottom"><!--header-bottom-->
            <div class="container">
                <div class="row">
                    <div class="col-sm-9">
                        <div class="navbar-header">
                            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                                <span class="sr-only">Toggle navigation</span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                            </button>
                        </div>
                        <div class="mainmenu pull-left">
                            <ul class="nav navbar-nav collapse navbar-collapse">
                                <li><a href="{{url('')}}" {{$page == 'home' ? 'class=active' : ''}}>Home</a></li>
                                <li><a href="{{url('products')}}" {{$page == 'products' ? 'class=active' : ''}}>Products</a></li>
                                <li><a href="{{url('blog')}}" {{$page == 'blog' ? 'class=active' : ''}}>Blog</a></li>
                                <li><a href="{{url('contact-us')}}" {{$page == 'contact_us' ? 'class=active' : ''}}>Contact Us</a></li>
                            </ul>
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="search_box pull-right">
                            <input type="text" placeholder="Search"/>
                        </div>
                    </div>
                </div>
            </div>
        </div><!--/header-bottom-->
    </header><!--/header-->

HERE,

  • {{Auth::check() ? Auth::user()->name : 'Account'}} checks if the user is logged in using check method of Auth. If the user is logged in, the login name is displayed. If the user is not logged in, the text Account is displayed
  • {{Auth::check() ? 'Logout' : 'Login'}} displayed Logout of the user is logged in and Login if the user is logged out
  • <a href="{{Auth::check() ? url('auth/logout') : url('auth/login')}}"> displays the URL for Logout if the user is logged in. Displays the URL for Login if the user is logged out.

Load the following URL to test the system

http://localhost/larashop/public/auth/login

Sign up for a new account

Try to login using the email address and password that you used to register

Your registered name will be displayed when you login successfully.

Summary

In this tutorial demonstrates how you can quickly develop an authentication system for Laravel 5 using the built in features.

What’s next?

The following tutorial builds a simple RESTful API that lists the products that we have. The API can be consumed by a mobile application assuming we develop a mobile app for our online store. The API can also be used by other websites that you would like to display your products.

Tutorial History

Tutorial version 1: Date Published 2015-08-30

Related Tutorials