Step-by-Step Guide to Mastering Laravel Authentication and Authorization

Nova Novriansyah
NovAI- PHP Laravel 101
6 min readJul 3, 2024

In this comprehensive guide, you will learn how to set up a Laravel project, configure the database, implement authentication, manage users and roles, implement authorization, and test your application using a browser.

Table of Contents

  1. Setting Up Your Laravel Project
  2. Configuring the Database
  3. Implementing Authentication
  4. Managing Users and Roles
  5. Implementing Authorization
  6. Testing Your Application

1. Setting Up Your Laravel Project

Requirements

  • Composer installed globally
  • PHP (minimum version according to Laravel’s requirements)

Steps

  1. Create a New Laravel Project: If you haven’t installed Laravel globally, use Composer to create a new Laravel project:
composer create-project --prefer-dist laravel/laravel my-laravel-auth

2. Navigate to Your Project Directory: Change into your project directory:

cd my-laravel-auth

2. Configuring the Database

Requirements

  • PostgreSQL server installed and running
  • Database credentials (username, password, database name, host)

Steps

  1. Create new database using your pgadmin named new_laravel_db

If you get the following error message, you need to add lines to you pg_ba.conf on you posgres server.

in my case, on my postgresql vm. You may adjust the path of your postgresql installation and pg_hba.conf file.

vi /etc/postgresql/14/main/pg_hba.conf

adding this line

  1. Configure .env File: Laravel uses the .env file in the root directory for environment-specific configuration. Copy .env.example to .env:
cp .env.example .env

2. Edit .env File: Update the database connection details according to your PostgreSQL setup:

DB_CONNECTION=pgsql
DB_HOST=192.168.3.187
DB_PORT=5432
DB_DATABASE=new_laravel_db
DB_USERNAME=postgres
DB_PASSWORD=zuruck

3. Implementing Authentication

Requirements

  • laravel/ui package installed

Steps

  1. Install Laravel/UI Package: Install the Laravel/UI package to use Laravel’s authentication scaffolding:
composer require laravel/ui

2. Generate Authentication Scaffolding: Generate the authentication scaffolding using the Vue.js preset:

php artisan ui vue --auth

Generated Files and Directories:

  • Views: Located in resources/views/auth/. These views include forms for login, registration, password reset, and email verification.
  • Routes: Added to routes/web.php. Authentication routes are defined using Laravel's routing system.
  • Controllers: Controllers are created under app/Http/Controllers/Auth/. These controllers handle user authentication actions.

3. Run Migrations: Laravel’s authentication system requires database tables. Run migrations to create these tables:

php artisan migrate
before migrate
migrate
table generated post migrate

4. Managing Users and Roles

Requirements

  • spatie/laravel-permission package installed

Steps

  1. Install Spatie Laravel Permission Package: Install the Spatie Laravel Permission package for managing roles and permissions:
composer require spatie/laravel-permission

2. Publish Configuration and Migrate: Publish the configuration file and run migrations to set up roles and permissions tables:

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
php artisan migrate

This command will execute the migration files, including any that are related to the Spatie Permission package, ensuring that the necessary tables (permissions, roles, model_has_roles, role_has_permissions, model_has_permissions) are created in your database.

5. Implementing Authorization

Steps

  1. Define Roles and Permissions: Create roles and permissions in your application. Example seeding roles:
// File: database/seeders/RoleSeeder.php

<?
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RoleSeeder extends Seeder
{
public function run()
{
$roleAdmin = Role::create(['name' => 'admin']);
$roleUser = Role::create(['name' => 'user']);

Permission::create(['name' => 'manage users'])->assignRole($roleAdmin);
Permission::create(['name' => 'edit profile'])->assignRole($roleUser);
}
}

2. Implement Policies and Gates:
Define policies and gates to control access to resources in your application.

php artisan make:policy PostPolicy --model=Post

Example policy:

// File: app/Policies/PostPolicy.php

namespace App\Policies;

use App\Models\Post;
use App\Models\User;

class PostPolicy
{
public function update(User $user, Post $post)
{
return $user->id === $post->user_id;
}
}

3. Register Policies:
Register policies in the AuthServiceProvider:

// File: app/Providers/AuthServiceProvider.php

namespace App\Providers;

use App\Models\Post;
use App\Policies\PostPolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
Post::class => PostPolicy::class,
];

public function boot()
{
$this->registerPolicies();
}
}

6. Check Vite Configuration

Vite is a modern build tool for front-end development that aims to provide a faster and more efficient development experience compared to traditional bundlers like Webpack.

Vite is designed to streamline the front-end development workflow by leveraging modern browser features and optimizing build processes. It’s particularly beneficial for projects that prioritize speed, developer experience, and efficient use of modern JavaScript features and APIs.

Requirements

  • Node.js version 15 or higher and npm (or yarn) installed globally

Steps

  1. Install Vite: Install Vite for fast front-end development:
npm install -g vite

Ensure that your Vite configuration (vite.config.js or vite.config.ts in the root of your Laravel project) is correctly set up to output the manifest.json file. Here's a basic example of how it might look:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
plugins: [
laravel({
input: [
'resources/sass/app.scss',
'resources/js/app.js',
],
refresh: true,
}),
vue({
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false,
},
},
}),
],
resolve: {
alias: {
vue: 'vue/dist/vue.esm-bundler.js',
},
},

build: {
outDir: 'public/build', // Output directory for build artifacts
manifest: true, // Generate manifest.json file
},
});
npm run dev

Generate manifest.json

Run Vite Build: After updating your configuration, run the Vite build command in your terminal. This will trigger Vite to process your assets, compile them, and generate the manifest.json file along with other build artifacts.

vite build

move the manifest.json from public/build/.vite to public/build

7. Testing Your Application

Steps

  1. Serve Your Application: Start the Laravel development server:
php artisan serve

2. Access Your Application: Open your web browser and navigate to http://localhost:8000.

3. Test Authentication:

  • Register a new user and log in.
  • Test password reset and email verification functionalities.

4. Manage Users and Roles:

  • Assign roles to users using Tinker or a seeder.
  • Check user roles using a route or Tinker.

5. Test Authorization:

  • Create protected routes using middleware.
  • Use gates and policies to control access to specific routes and actions.

Conclusion

By following this step-by-step guide, you have learned how to set up a Laravel project, configure the database, implement authentication, manage users and roles, implement authorization using gates and policies, and test your application using a web browser. Laravel’s built-in features and packages like laravel/ui and spatie/laravel-permission make it straightforward to build secure and scalable applications with robust user management and access control functionalities.

--

--

Nova Novriansyah
NovAI- PHP Laravel 101

C|CISO, CEH, CC, CVA,CertBlockchainPractitioner, Google Machine Learning , Tensorflow, Unity Cert, Arduino Cert, AWS Arch Cert. CTO, IT leaders. Platform owners