Beginner’s Guide to Laravel: Let’s do authentication in 10 minutes

Beginner’s Guide to Laravel: Let’s do authentication in 10 minutes

Introduction

Authentication refers to the process of verifying the identity of users accessing a web application. It ensures that only authorized users are allowed to perform certain actions or access specific resources within the application. Laravel, being a popular PHP framework, provides built-in support for authentication through various mechanisms.

Here, we will use Larael Fortify and Jetstream to achieve this. Laravel Jetstream is an authentication scaffolding for Laravel applications. It comes with Laravel Fortify, which is a backend authentication package that provides the necessary logic for user registration, login, and other authentication features. Here are the steps to set up authentication in Laravel using Fortify and Jetstream:

Create a New Laravel Project

Assuming you have Laravel installed on your system, open your terminal and run the following command to create a new Laravel project if you had not already:

composer create-project laravel/laravel my-auth-app
cd my-auth-app

Install Jetstream with Livewire

Jetstream supports two front-end stacks, Livewire and Inertia. Livewire is more suitable for traditional server-side applications, while Inertia is a bit more modern and works well with single-page applications. Here, I will use Livewire.

composer require laravel/jetstream
php artisan jetstream:install livewire

Install Laravel Fortify

Laravel Fortify provides the authentication logic for Jetstream. Run the following command to install Fortify:

composer require laravel/fortify
php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider"
php artisan fortify:install

Run Migrations

In Laravel, migrations are a way to manage the database schema and version control for your application. Migrations allow you to define the structure of your database tables, including the creation, modification, and deletion of tables and columns. By using migrations, you can easily collaborate with other developers and keep track of changes to the database schema over time.

Migrations are written in PHP and are stored in the database/migrations directory of your Laravel project. Each migration file represents a specific database schema change and includes two methods: up() and down(). The up() method defines the actions to be performed when running the migration, and the down() method specifies how to undo those actions in case of a rollback.

In this step, we will run the database migrations to create the necessary tables for authentication:

php artisan migrate

This will execute all the pending migrations and create a user table with the specified columns.

If this command does not run successfully, then you have not set up your database correctly. You can follow the following instructions.

Setting up PostgreSQL (pgsql) Database

We will use a PostgreSQL database over MySQL because of its robust support for complex data types and advanced features. PostgreSQL provides a wide range of data types. These advanced data types allow you to model and manipulate complex data structures directly in the database, reducing the need for complex application logic.

Windows

Download the PostgreSQL installer for Windows from the official PostgreSQL website: postgresql.org/download

Run the installer and follow the prompts to install PostgreSQL.

During installation, set the password for the default postgres user.

After installation, you can access PostgreSQL using the psql command-line client or pgAdmin, which is usually installed with PostgreSQL.

MacOS

On macOS, you can use the pgAdmin app to install and manage PostgreSQL instead of using Homebrew. Here's the procedure:

  1. Download pgAdmin from the official pgAdmin website: https://www.pgadmin.org/download/pgadmin-4-macos/.

  2. After downloading the macOS version, open the downloaded .dmg file.

  3. Drag the pgAdmin icon into the "Applications" folder to install it.

  4. Once installed, open pgAdmin from the "Applications" folder.

  5. Upon the first launch, pgAdmin will prompt you to set a master password. Enter a secure password to protect your pgAdmin instance.

  6. After setting the master password, pgAdmin will open in your default web browser. You can access it at http://127.0.0.1:5434 (or another port if you've configured it differently).

  7. In the pgAdmin interface, you'll need to set up a server to connect to your local PostgreSQL instance:

  8. Click on "Add New Server" (or the "Add a connection to a server" icon).

  9. In the "General" tab, give your server a name (e.g., "Local PostgreSQL").

  10. In the "Connection" tab, set the following parameters:

    Host name/address: localhost (or 127.0.0.1).

    Port: 5432 (the default port for PostgreSQL).

    Maintenance database: postgres.

    Username: postgres.

    Password: Enter the password you set during PostgreSQL installation.

  11. Click "Save" to save the server configuration.

  12. Once you've saved the server configuration, you can expand the "Servers" node in the pgAdmin sidebar to see your newly added server.

  13. Double-click on your server to open a connection to it. You'll be prompted to enter the master password you set earlier for pgAdmin.

  14. You now have a working pgAdmin interface to manage your PostgreSQL databases. You can create new databases, manage tables, execute SQL queries, and more.

Ubuntu Linux

Update the package index on Ubuntu:

sudo apt update

Install PostgreSQL

sudo apt install postgresql postgresql-contrib

After installation, PostgreSQL should start automatically. You can check its status with

sudo systemctl status postgresql

By default, a Postgres user is created, and you can access PostgreSQL with the psql command-line client:

sudo -u postgres psql

Create a Database

Once you’ve set it up, you can proceed to create an empty database. This empty database will be filled with our migrations once the migrate command has been run.

Add .env Variables

The .env file holds environment variables for your application, including database connection details, and allows you to easily switch between different environments (e.g., local development, production) without modifying the code.

Locate the .env.example file in the root directory of your Laravel project and rename it to .env. Open the .env file with a text editor, and you'll find several variables that need to be configured. Look for the following database-related variables:

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1   # Replace with your PostgreSQL host (usually 'localhost' if on the same machine).
DB_PORT=5432        # Default PostgreSQL port.
DB_DATABASE=your_database_name    # Replace with the name of the database you created in PostgreSQL.
DB_USERNAME=your_username         # Replace with your PostgreSQL username.
DB_PASSWORD=your_password         # Replace with your PostgreSQL password.

Make sure to save the changes in the .env file.

Finally, you can run the database migrations to create the necessary tables:

php artisan migrate

Set Up a Front-end Scaffolding

You need to set up front-end scaffolding for your preferred stack. For Livewire, run:

npm install
npm run dev

The npm install command uses npm (Node.js Package Manager) to install the required JavaScript packages and dependencies for your Laravel application. These packages are necessary for the front-end functionality.

The npm run dev command compiles the front-end assets of your Laravel application, such as JavaScript and CSS files, from the resources directory to the public directory. After running this command, your application will be ready to display its front-end features.

Configure Fortify

You can configure Fortify options in the config/fortify.php file. This allows you to customize authentication features, such as password reset options, email verification, and more.

Generate App Key

In Laravel, the app key is a random string used for encrypting various data, including session data, cookies, and other sensitive information. It is an essential security feature that helps protect user data and maintain the integrity of your application. The app key is stored in the .env file of your Laravel project.

To generate a new app key, open your terminal or command prompt, and run the following command:

php artisan key:generate

Serve your application

Serving an application in Laravel means making your Laravel project accessible over the web so that users can interact with it through their web browsers. When you serve a Laravel application, it means you are running a web server that listens for incoming HTTP requests from clients (usually web browsers) and responds with the appropriate content generated by your Laravel application.

Use the following command to serve an application:

php artisan serve

Open your web browser and visit http://127.0.0.1:8000 to access your Laravel application.

The built-in server is intended for local development and testing purposes and should not be used for production deployment.

Test Authentication

With everything set up, you can now test your authentication system by visiting the http://127.0.0.1:8000/register and http://127.0.0.1:800/login routes in your application.

Outro

In this blog post, we explored the process of setting up authentication in a Laravel application using Fortify and Jetstream in just 5 minutes. Authentication is crucial for securing web applications and ensuring that only authorized users can access specific resources.

We started by creating a new Laravel project and then installed Jetstream with Livewire, which is a front-end stack suitable for traditional server-side applications. Laravel Jetstream provides out-of-the-box authentication features, while Livewire enables a seamless user experience.

Next, we installed Laravel Fortify, the backend authentication package that works with Jetstream to handle user registration, login, and other authentication functionalities.

To manage the database schema and version control, we leveraged Laravel's migration feature. Migrations allowed us to create the necessary user table and columns for authentication. PostgreSQL, with its robust support for complex data types and advanced features, emerged as the preferred database choice.

We then explored setting up PostgreSQL on different operating systems, including Windows, macOS, and Ubuntu Linux, using either the official PostgreSQL installer, pgAdmin app, or package manager.

Additionally, we covered configuring the .env file to store environment variables, enabling easy switching between different environments without modifying the code.

Finally, we set up front-end scaffolding using npm to compile the assets and tested the authentication system by visiting the appropriate routes.

By following these simple steps, developers can swiftly implement authentication in their Laravel applications, ensuring a secure and efficient user experience for their users.

As you venture further into the world of Laravel development, keep in mind the importance of authentication and how it enhances the overall security and reliability of your web applications. See you in the next post!