Complete Guide for Laravel Authentication

Last Updated: June 30, 2021

In this tutorial, I am going to implement a Laravel authentication system

Database configuration
You can put the database credentials in the .env file

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

In database>migration location you can find two files that will create tables needed for Auth

You can run the following command inside the terminal

php artisan migrate

This will generate two tables called users and password_resets in your database. Now you have done the Authentication.

Now you run the following command in your terminal

php artisan make:auth

It is time to test your code

Register Page
You can load the built-in register page at http://localhost/public/register

Login Page
You can load the built-in login page at http://localhost/public/login

Password Reset Page
You can see the password reset page at the location http://localhost/dev/cc/laravel/user/public/password/reset

Without using Scaffolding Laravel Packages you can create authentication manually just by managing Laravel classes.

First, we will create LoginController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /**
     * Handle an authentication attempt.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function authenticate(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();

            return redirect()->intended('dashboard');
        }

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

You submit the form with username and the password and the attempt method is used to handle authentication attempt’s from your application’s “login” form.

If authentication is successful, you should regenerate the user’s session to prevent session fixation: