Laravel 6.0 is out! Check out Build a Laravel 6 CRUD App with Authentication to learn what new things Laravel can do for you.
This blog post covers Laravel 5.8.

TL;DR: Laravel is a great PHP framework. Currently, it is the most starred PHP project on Github and a lot of companies and people all over the world use it to build amazing applications. In this tutorial, I'll show you how easy it is to build a web application with Laravel and add authentication to it without breaking a sweat. Check out the repo to get the code.

Laravel is a free, open-source PHP framework designed for building web applications with an expressive and elegant syntax. Laravel has a high level of abstraction which shields the common developer from complex inner workings. Laravel saves you time and effort because it ships with a lot of features out of the box. These amazing features include:

  • Database Migrations
  • Eloquent ORM
  • Authorization and Policies
  • Scheduler
  • Queuing

Laravel makes good use of already written and well tested components from the PHP community. It is one of the few frameworks that actually comes with development environments such as Homestead and Valet. The documentation is very detailed and there is a large community based around Laravel. Some of the notable communities are,,, and

"Laravel is one of the few frameworks that actually comes with development environments such as Homestead"

We'll be building a simple character listing app with Laravel 5.8. Our app will simply list 10 Game of Thrones characters and their real names. Once we add authentication to the app, all logged-in users will have the privilege of knowing these celebrity characters personally.

Let's Get Started

Laravel utilizes Composer to manage its dependencies. So, before using Laravel, make sure you have Composer installed on your machine. We can install Laravel by issuing the Composer create-project command in your terminal like so: composer create-project --prefer-dist laravel/laravel GOT or using the laravel installer.

It's actually faster to spin up a new app using the laravel command like so: laravel new GOT . Check out the Laravel docs to learn how to set up the laravel installer.

If you used the laravel installer command to create a new app, then you have to run composer install immediately after the previous command to install all the dependencies.

Now run the following in your terminal to launch your application:

php artisan serve

Explore Directory Structure

Laravel applications follow the Model-View-Controller design pattern.

Model View Controller Diagram

(Source: Self Taught Coders)

In a nutshell,

  • Models query your database and return the necessary data.
  • Views are pages that render data
  • Controllers handle user requests, retrieve data from the models, and pass them to the views.

Read more about MVC here.

The app directory is the meat of your Laravel application. It houses the following directories:

  • Console - Contains all your Artisan commands
  • Http - Contains all your controllers, middleware, requests, and routes file
  • Providers - Contains all your application service providers. You can read more about Service Providers here
  • Events - Contains all your event classes
  • Exceptions - Contains your application exception handler and custom exception classes
  • Jobs - Contains all the jobs queued by your application
  • Listeners - Contains all the handler classes for your events
  • Policies - Contains the authorization policy classes for your application. Policies are used to determine if a user can perform a given action against a resource.

The other directories namely:

  • boostrap contains your framework autoloading files and generated cache files
  • config contains your app's configuration files
  • database contains your database migrations and seeds
  • public contains your assets (images, JavaScript, css etc)
  • resources contains your views and localization files
  • storage contains all your compiled Blade templates, file caches, and logs
  • tests contains all your tests
  • vendor contains your app dependencies

Setting Up The Controller

Open up your terminal and in the project root directory, run the command below to create a ListController.

php artisan make:controller ListController

Open up app/Http/Controllers/ListController.php and configure it like so:


namespace App\Http\Controllers;

class ListController extends Controller
    public function show()
       $characters = [
         'Daenerys Targaryen' => 'Emilia Clarke',
         'Jon Snow'           => 'Kit Harington',
         'Arya Stark'         => 'Maisie Williams',
         'Melisandre'         => 'Carice van Houten',
         'Khal Drogo'         => 'Jason Momoa',
         'Tyrion Lannister'   => 'Peter Dinklage',
         'Ramsay Bolton'      => 'Iwan Rheon',
         'Petyr Baelish'      => 'Aidan Gillen',
         'Brienne of Tarth'   => 'Gwendoline Christie',
         'Lord Varys'         => 'Conleth Hill'

       return view('welcome')->withCharacters($characters);

view('welcome')->withCharacters($characters) indicates that we are passing the $characters array to a view called welcome.blade.php. We'll create that view later in this post.

Setting Up The Model

Laravel models are stored by default in the root of the app directory. The User model ships with the Laravel framework. Only the User model is needed in this application so we won't create any additional models. However, if you want to create more models, you can simply run the command below like so:

php artisan make:model <modelName>

where <modelName> represents the name of the model you want to create.

Setting Up The Routes

Open up routes/web.php and configure it like so:

| Application Routes
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.

Route::get('/', 'ListController@show');

Once a request hits the / route, it invokes the show method of the ListController and renders the returned value in the welcome view. We'll configure the welcome view later in this post.

Setting Up Authentication

One fascinating thing about Laravel is that it comes with authentication out of the box. You just have to configure it. Open up your terminal and run this command:

php artisan make:auth

Be careful to only do this on fresh applications.

screen shot 2016-06-19 at 2 34 10 pm

As you can see, some files have been copied into our application, the routes have also been updated. The route file has been populated with additional information like so:

screen shot 2016-06-19 at 3 22 39 pm

Auth::routes() is a method that cleanly encapsulates all the login and register routes.

Now the views needed for authentication are in the resources/views/auth directory. The base layout for our application has also been configured in the resources/views/layouts directory. All of these views use the Bootstrap CSS framework, but you are free to customize them however you wish.

Open up your welcome.blade.php and configure it like so:

<div class="container">
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <div class="panel panel-success">
                <div class="panel-heading">List of Game of Thrones Characters</div>
                      <!-- Table -->
                      <table class="table">
                              <th>Real Name</th>
                          @foreach($characters as $key => $value)
                              <td>{{ $key }}</td><td>{{ $value }}</td>
              <a href="/login" class="btn btn-info"> You need to login to see the list 😜😜 >></a>

Here, we are looping through the $characters array data passed from the ListController for appropriate rendering in the welcome view.

Auth::check() - You can check if a user is authenticated or not via this method from the Auth Facade. It returns true if a user is logged-in and false if a user is not. Check here for more about how Facades work in Laravel.

Auth::guest() - This does the opposite of Auth::check(). It returns true if a user is not logged in and false if a user is logged in. Check here to see all the methods you can call on the Auth Facade.

Now that we have all the routes and views setup, your application should look like this:

Landing Page

Landing Page

Login Page

Login Page

Register Page

Register Page

Run Migrations

Migrations are like version control for your database, allowing a team to easily modify and share the application's database schema. In Laravel, they are placed in the database/migrations directory. Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations.

Luckily for us, the user migration files come by default with a fresh Laravel install. Check the database/migrations directory to ensure you have at least two migration files named xxx_create_users_table.php and xxx_create_password_resets_table.php where xxx represents the timestamp.

Now, run this command from your terminal:

php artisan migrate

The users and password_resets table will be created by running this command. Ensure the appropriate database name has been set in your .env file. The value should be assigned to this DB_DATABASE constant.

Path Customization

Open up LoginController.php in the app/Http/Controllers/Auth directory and change the $redirectTo variable to / like so:

// app/Http/Controllers/Auth/LoginController.php
* Where to redirect users after login / registration.
* @var string
protected $redirectTo = '/';

redirectTo can be configured to whatever route you want the user to be redirected to just after registration or login. In our case, the user should be redirected to the landing page.

Repeat this process for the RegisterController as well at app/Http/Controllers/Auth/RegisterController.php.

Now, go ahead and register. It should register you successfully and log you in like so:

Landing Page while authenticated

Using the Auth Middleware

Middlewares provide a convenient mechanism for filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further. The app/Http/Middleware directory contains several middleware.

Let's check out how the auth middleware works.

Add a new route to your routes/web.php file like so:

Route::get('/got', [
  'middleware' => ['auth'],
  'uses' => function () {
    echo "You are allowed to view this page!";

Now, log out, then try to access that route (http://localhost:8000/login) and you will be redirected back to the /login route.

The Laravel auth middleware intercepted the request, checked if the user was logged-in, discovered that the user was not logged-in, then redirected the user back to the login page.

Setting up the built-in authentication with Laravel is pretty straightforward, but limited. With Auth0, you'll have access to an easy-to-use dashboard, the ability to integrate social identity providers, two-factor authentication, passwordless login, and more. And luckily, it's just as easy to integrate with your Laravel application! Let's check it out.

Aside: Using Auth0 with Laravel

Auth0 issues JSON Web Tokens on every login for your users. This means that you can have a solid identity infrastructure, including single sign-on, user management, support for social identity providers (Facebook, Github, Twitter, etc.), enterprise identity providers (Active Directory, LDAP, SAML, etc.) and your own database of users with just a few lines of code.

We can easily set up authentication in our Laravel apps with Auth0's Login Page. If you don't already have an Auth0 account, sign up for one now. Navigate to the Auth0 management dashboard, select Applications from the navigational menu, then select the app you want to connect with Laravel.

Step 1: Install and Configure Auth0 plugin

Follow the instructions here to configure the Auth0 plugin.

Step 2: Register the callback

Head over to your Auth0 dashboard and register Allowed Callback URLs, Allowed Logout URLs

Open up your routes and add this:

Route::get('/auth0/callback', '\Auth0\Login\Auth0Controller@callback');

Step 3: Include the Auth0 Login Page

Open up welcome.blade.php and configure it like so:


    <a href="/auth0/login" class="btn btn-primary">login</a>

When the login button is clicked, users are redirected to Auth0's Login Page.

Auth0 login screen

Step 4: Configure Routes.php

Add this to your routes.php file:

Route::get('/auth0/login', function() {
        $domain = env('AUTH0_DOMAIN');
        $clientId = env('AUTH0_CLIENT_ID');
        $redirectUri = env('AUTH0_CALLBACK_URL');
        $authorizeUrl = sprintf(
        return redirect($authorizeUrl);

Now, once a user registers, it stores the user information in your Auth0 dashboard. We can retrieve this info using the Auth0::getUser() method. We can also hook onto the onLogin event using Auth0::onLogin(function(...)).

Access Token

Access can be restricted with Auth0 Middleware, just add this 'auth0.jwt' => 'Auth0\Login\Middleware\Auth0JWTMiddleware' in the $routeMiddleware array in app/Http/Kernel.php. Then use auth0.jwt middleware on your routes.

With Auth0, you can have all your users' information stored without having to run your own database. Auth0 provides powerful analytics about users signing up on your platform such as the browser the user logged in with, the location, device, number of logins and more, out of the box!

User Information

Important API Security Note: If you want to use Auth0 authentication to authorize API requests, note that you'll need to use a different flow depending on your use case. Auth0 idToken should only be used on the client-side. Access tokens should be used to authorize APIs. You can read more about making API calls with Auth0 here.

Wrapping Up

Well done! You have just built your first app with Laravel. Laravel is an awesome framework to work with. It focuses on simplicity, clarity and getting work done. As we saw in this tutorial, you can easily activate the built-in authentication to your Laravel applications. If you find yourself needing more, you can also integrate Auth0 just as easily.

Please, let me know if you have any questions or observations in the comment section. 😊