Setting Up Laravel 5.8 With Authentication & Role Based Access

Setting up your application with authentication & role-based access is much better fleshed out at the very beginning of a new project. There’s nothing worse than being 1 month deep into development and the client then requires login functionality and role-based access, trust me, I’ve been there.

In this latest tutorial, we will set up a new Laravel project, specifically version 5.8, in addition, we will set up the initial database tables and configure the authentication and role-based access. Let’s go.

Prerequisites

For easiness, I always use XAMPP, which installs PHP, Apache, and MySQL all together, this is totally up to you, though.

  1. PHP v7.1.3 or higher.
  2. Apache
  3. MySQL or similar.
  4. Composer (PHP Package Manager) which can be found here

Pre-note

Just so you are aware, for the tutorial, XAMPP was used, so the root file directory for the files is htdocs/myAppFolder/ – Just so you are aware why I am navigating to that folder when using composer!

Installing Laravel 5.8

The simplest way to get started with Laravel these days is to use Composer. Hopefully, you’ve used it before and you will already understand what it’s about. If not, it’s pretty straight forward, it downloads specified PHP packages and installs them into your project directory seamlessly.

Step 1

So that being said, let us boot up a terminal and navigate to your projects root directory, for this tutorial, C:/XAMPP/htdocs/ was used.

Once you’ve navigated to your project root folder with the terminal, run the following command (Noting the last string is the name of the folder where the Laravel files will be downloaded too –

composer create-project --prefer-dist laravel/laravel project

After the files installed, you should now have a new folder within the /htdocs/ folder named project.

Step 2

  1. Find the server.php file within your project directory and rename it index.php.
  2. Then, move the .htaccess file from project/public/ to the root project/ folder.
  3. Now, start up your Apache and MySQL via the XAMPP control panel, or using your own custom setup.
  4. Open a browser and navigate to localhost:80/project (or replace project with your own project name), you should be presented with the Laravel homepage.

Configuring Laravel with your Database

Step 1

If this is a brand new MySQL install, you will need to create a new database, for this example, the new database was named project_database. If not, happy days, just remember which database you want to use when we configure the settings.

Step 2

Find the .env file within your root folder, open it, and edit the MySQL settings like below –

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=project_database
DB_USERNAME=root
DB_PASSWORD=

Step 3

For good measure, locate the database.php file within your project config folder and edit the MySQL settings again –

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'project_database'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

Great, that’s the database connection sorted!

Bootstrapping the application with authentication

Laravel comes with a brilliant templating system, namely Blade Templates. These can be used elegantly to allow you to only really worry about the content of your pages. The layout file will hold all the metas, CSS and JS files for you. This is swiftly setup whilst Laravel cleanly installs the authentication system for you. So, let’s run the command.

Step 1

  • Navigate to your project folder within a terminal
  • Execute the following – php artisan make:auth
  • Then execute php artisan migrate

Your project will now be prepped for general user authentication, a new layouts folder and file will have been generated, in addition, a new auth folder with relevant views and a new home view also. You can see all of these in the resources/views folder.

Step 2

Locate the app.blade.php file within the resources/views/layouts folder and edit the following line

<!-- Styles -->
 <link href="{{ asset('css/app.css') }}" rel="stylesheet">

To

<!-- Styles -->
<link href="{{ asset('public/css/app.css') }}" rel="stylesheet">

Recap & testing the initial authentication

So, up to now, we have,

  • Setup our environment
  • Created our project with Laravel
  • Set up our database connections
  • Added blade layout templating
  • Added various views
  • Added a new users table to our database with the following fields –
    • id
    • name
    • email
    • email_verified_at
    • password
    • remeber_token
    • created_at
    • updated_at

All this has been done by no real manual coding, pretty much all via the CLI which is pretty god damn epic!

Next, we need to test the authentication system works, so let’s navigate to the register page –

  • Goto http://localhost/project/register
  • Enter your registration details and hit the register button.
  • This will then proceed to log you in.

That is it, registrations and logins for your project are completely set up. Next up is to set up role-based access.

Setting up Role-Based access

Now, rather than me duplicate a really great tutorial, I will reference it here. It’s been trialed and tested and works elegantly. The writer has clearly set out each factor of setting up role-based access and it even works from Laravel 5.4 onwards. Make sure you come back to the next section to see how to start utilizing the roles!

Follow this tutorial for completing the authentication and role-based access – Laravel Role Based Access Tutorial

Credit goes to Everton zp on medium for the above tutorial.

Utilizing Authentication & Role Based Access

Let’s start putting Authentication and role-based access to further use inside our code. This data can be utilized in the likes of your controllers but, can also be used within views. This is when you can start showing certain things to certain users, for example, a super-user menu.

The following code checks to see if the user is logged in then makes further checks to see if the user has the ‘Super’ role assigned to them.

<!-- if user is logged in -->
@if (Auth::check())

        <!-- if user has 'Super' role assigned to them. -->

        @if (Auth::user()->hasRole("Super"))

        <div class="sidebar-heading">
                Admin
            </div>

        <!-- Nav Item - Pages Collapse Menu -->

       <li class="nav-item">
            <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseLinks"
                aria-expanded="true" aria-controls="collapsePages">
                <i class="fas fa-fw fa-cog"></i>
                <span>Manage</span>
            </a>

            <div id="collapseLinks" class="collapse" aria-labelledby="headingPages" data-parent="#accordionSidebar">
                <div class="bg-white py-2 collapse-inner rounded">
                    <h6 class="collapse-header">Manager:</h6>
                    <a class="collapse-item" href="{{ route('users.index')}}">Users</a>
                    <a class="collapse-item" href="{{ route('roles.index')}}">Roles</a>
                </div>
            </div>
        </li>

        @endif <!-- End Is SuperUser Check -->

@endif <!-- End Auth Check -->

These little method calls can be used in a variety of ways and in a variety of places, they become very handy for large scale projects. Especially if you need to hide things for certain users and even prevent users performing specific tasks, etc.

Summary

This article is the bare essentials you need to get Laravel up and running with authentication and role-based access. There is certainly more that can be done, which I will delve into in further articles. Things like user management from an admin perspective and others like making sure the password reset email functionality works correctly.

 

SHARE ON

The Author: Dan Englishby

Setting Up Laravel 5.8 With Authentication & Role Based Access

You May Also Like

Leave a Reply

Your email address will not be published.