How to implement password login in Laravel

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

Laravel is a powerful and popular PHP framework for web application development. It provides robust features for building secure and scalable web applications with ease. One of the fundamental features Laravel offers is a seamless authentication system. In this tutorial, we’ll explore how to implement a password login system in Laravel from the ground up. We’ll start with the basics and progressively delve into more advanced concepts, including form validation, password hashing, and middleware for authenticated sessions.

Prerequisites

Before you begin, make sure you have the following installed:

  • Laravel (8.x or later recommended)
  • PHP (7.3 or later)
  • Composer
  • A working database setup (MySQL, Postgres, SQLite, etc.)

Note: This guide assumes you have a basic understanding of Laravel and MVC architecture.

Setting Up Authentication Scaffolding

Laravel provides a convenient command to set up the authentication scaffolding. Use Artisan, the built-in command-line tool, to create the necessary controllers, views, and routes:

php artisan ui bootstrap --auth

This command will generate the views, routes, and controllers needed for a basic login and registration system. To compile your front-end assets, run:

npm install
npm run dev

Configure your ‘.env’ file to connect to the database and then migrate the default user table:

php artisan migrate

Creating the Login Route

With the authentication scaffolding in place, the login route will be defined within the ‘routes/web.php’ file.

Auth::routes();

Visit ‘/login’ to see the default login form provided by Laravel. This form is backed by the ‘App\Http\Controllers\Auth\LoginController’.

Understanding the LoginController

Laravel’s ‘LoginController’ contains the logic for handling login requests. The ‘authenticate’ method, which you can override, is where you’ll typically customize login behavior. Below is the default method:

public function authenticate(Request $request)
{
    $credentials = $request->only('email', 'password');

    if (Auth::attempt($credentials)) {
        // Authentication passed...
        return redirect()->intended('dashboard');
    }
}

When the user submits the login form, the above ‘authenticate’ method is triggered. ‘Auth::attempt’ is a built-in Laravel function that validates user credentials against the database. If the authentication is successful, the user gets redirected to the intended page, often the dashboard.

Validating Input Data

Data validation is crucial in any login system. Laravel’s ‘Request’ class offers a ‘validate’ method that you can employ for input validation rules. Modify the ‘authenticate’ function with validation rules:

public function authenticate(Request $request)
{
    // Validate the form data
    $credentials = $request->validate([
        'email' => 'required|email',
        'password' => 'required'
    ]);

    // Authenticate the user
    if (Auth::attempt($credentials)) {
        // Authentication passed...
        return redirect()->intended('dashboard');
    }

    // Authentication failed...
    return back()->withErrors([
        'email' => 'The provided credentials do not match our records.',
    ]);
}

The ‘validate’ method throws an exception that will redirect the user back to the form with the validation errors.

Password Hashing and Security

Laravel includes built-in hashing support which you should always use for passwords. By default, Laravel uses the bcrypt hashing algorithm. When registering a user, ensure their password is hashed:

$user = User::create([
    'name' => $request->name,
    'email' => $request->email,
    // Use the Hash facade to secure the password
    'password' => Hash::make($request->password),
]);

Never store plaintext passwords in the database. Laravel’s ‘User’ model automatically hashes passwords when setting the ‘password’ attribute, assuming you are using the ‘Illuminate\Support\Facades\Hash’ facade.

Advanced: Custom Authentication Guards

Laravel’s authentication system is highly flexible and allows you to define custom guards. Guards define how users are authenticated for each request. For instance, you can have a separate guard for your web admins or API users.

To create a custom guard, you must define it in the ‘config/auth.php’ file, and most likely, you’ll create a custom provider as well. Here’s an example of a custom guard configuration:

'guards' => [
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
],
'providers' => [
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],
],

To authenticate with a custom guard, use:

if (Auth::guard('admin')->attempt($credentials)) {
    // Admin authentication passed...
}

Incorporating Middleware

Laravel middleware ensures that only authenticated users can access certain routes. Middleware can redirect guests to the login screen and protect routes. The ‘auth’ middleware is automatically applied to your routes when using the ‘–auth’ option while setting up authentication scaffolding:

Route::middleware('auth')->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
});

Any attempt to access ‘/dashboard’ by guests will be redirected to the login page.

Conclusion

We’ve covered how to implement a password login system in Laravel. Starting from the setup of basic authentication scaffolding, we’ve delved into customizations and security practices like input validation and password hashing. The flexibility of Laravel’s auth system also allows for complex scenarios involving custom guards and middleware. With these skills, you’re now equipped to implement robust authentication in your Laravel applications.