Laravel Login and Register

Posted on

Laravel Login and Register Tutorial: Step-by-Step

The login feature is part of user authentication, where users enter their email and password to access restricted areas of your application. Laravel provides several ways to create a login feature. In this article, I will explain two ways to create a Laravel login and register feature.

There are several ways to create a Laravel login feature, and the best choice depends on your needs:

  • Laravel Breeze (in this article): Ideal for simple applications that require basic authentication with a quick setup.
  • Manual Login (in this article): Best choice if you want to understand how authentication works in Laravel and need full control.
  • Laravel Fortify: Great for applications that require full control over the authentication backend without tying it to a specific frontend.
  • Laravel Jetstream: Best choice for complex applications that require full authentication features and team management.

If you want to make login faster and easier, Laravel Breeze is the perfect choice. Breeze is a simple authentication starter kit with login, registration, and password reset.

Step 1: Instal Laravel Breeze

First, install Laravel Breeze with the following command:

composer require laravel/breeze --dev
php artisan breeze:install

Then options will appear like this:

Laravel Login and Register Tutorial: Using Breeze

The stack you choose depends on your project needs. Here are some explanations to help you decide:

  • Blade with Alpine:
    • Uses Blade (Laravel’s default templating engine) and Alpine.js (a lightweight JavaScript framework).
    • This is ideal if you want a simpler approach with minimal interactivity.
  • Livewire (Volt Class API) with Alpine:
    • Uses Livewire to create interactive frontend components without leaving Blade.
    • The Volt Class API is the traditional way to write Livewire components.
    • This is great if you want to build more interactive apps and still want to use Blade.
  • Livewire (Volt Functional API) with Alpine:
    • It also uses Livewire but with a newer functional API (Volt).
    • This is great if you want to use new features and a more modern approach to writing components.
  • React with Inertia:
    • Uses React (a frontend JavaScript framework) with Inertia.js.
    • This is great if you’re already familiar with React or want to build a SPA (Single Page Application) app.
  • Vue with Inertia:
    • Uses Vue.js (a JavaScript framework for the front end) together with Inertia.js.
    • Great if you prefer Vue.js or want to build an application with a SPA approach.
  • API only:
    • Only provides an API without a built-in frontend.
    • Great if you are planning an application that will only be used as a backend and want the frontend to be built separately (e.g. with React, Vue, or a mobile app).

Suggestions:

  • If you are just starting out and want to use Blade, choose “Blade with Alpine”.
  • If you want to build an application with more interactivity but still use Blade, choose one of the Livewire options.
  • If you are interested in using React or Vue for the front end, choose one of the Inertia options.
  • If you are still confused, I recommend starting with “Blade with Alpine” to get a basic understanding first.

Then if there is an option from “Which testing framework do you prefer?” choose “PHPUnit“. Then use the following command.

npm install && npm run dev

Step 2: Use Breeze

Once Breeze is installed, you have the login, registration, and password reset features ready to go. You can access the login page at /login and the registration page at /register.

Breeze uses Blade as its templating engine, and all the views are already created for you in resources/views/auth.

Step 3: The Results

With Breeze, you don’t need to write a lot of code. It’s a quick and easy way to create a login feature in Laravel.

Laravel Login and Register using breeze
Login & Register Page Using Breeze Laravel

Let’s start with the manual approach. This is the way where you create the entire login and register feature from scratch. This is the best approach to learning and understanding how authentication works in Laravel.

Step 1: Make a Controller

First, we will create a controller that will handle login, register, and logout:

php artisan make:controller AuthController

Then, open the AuthController.php file and add the following code:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function showLoginForm()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required'],
        ]);

        if (Auth::attempt($credentials)) {
            return redirect()->route('dashboard');
        }

        return back()->withErrors(['email' => 'Login failed. Please check your email and password.']);
    }

    public function showRegisterForm()
    {
        return view('auth.register');
    }

    public function register(Request $request)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        return redirect()->route('login')->with('success', 'Registration successful. Please login.');
    }

    public function logout()
    {
        Auth::logout();
        return redirect()->route('login');
    }
}

Step 2: Make a View

Next, we create a display for login and register.

Login View

Create a new file resources /views/auth/login.blade.php and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
</head>
<body>
    <h2>Login</h2>
    <form action="{{ route('login') }}" method="POST">
        @csrf
        <label>Email:</label>
        <input type="email" name="email" required><br><br>
        <label>Password:</label>
        <input type="password" name="password" required><br><br>
        <button type="submit">Login</button>
    </form>

    <p>Don't have an account? <a href="{{ route('register') }}">Register here</a></p>

    @if ($errors->any())
        <div style="color: red;">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
</body>
</html>

Register View

Create a new file resources /views/auth/register.blade.php and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register</title>
</head>
<body>
    <h2>Register</h2>
    <form action="{{ route('register') }}" method="POST">
        @csrf
        <label>Name:</label>
        <input type="text" name="name" required><br><br>
        <label>Email:</label>
        <input type="email" name="email" required><br><br>
        <label>Password:</label>
        <input type="password" name="password" required><br><br>
        <label>Confirm Password:</label>
        <input type="password" name="password_confirmation" required><br><br>
        <button type="submit">Register</button>
    </form>

    <p>Already have an account? <a href="{{ route('login') }}">Login here</a></p>

    @if ($errors->any())
        <div style="color: red;">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
</body>
</html>

Step 3: Make a Route

Now, let’s add routes for login, register, logout, and dashboard in routes /web.php:

use App\Http\Controllers\AuthController;

Route::get('/login', [AuthController::class, 'showLoginForm'])->name('login');
Route::post('/login', [AuthController::class, 'login']);

Route::get('/register', [AuthController::class, 'showRegisterForm'])->name('register');
Route::post('/register', [AuthController::class, 'register']);

Route::post('/logout', [AuthController::class, 'logout'])->name('logout');

Route::middleware(['auth'])->group(function () {
    Route::view('/dashboard', 'dashboard')->name('dashboard');
});

Step 4: Make a Dashboard View

Finally, we create a dashboard display that will be displayed after a successful login. Create a new file resources /views/dashboard.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
</head>
<body>
    <h1>Welcome to the Dashboard, {{ Auth::user()->name }}!</h1>
    <form action="{{ route('logout') }}" method="POST">
        @csrf
        <button type="submit">Logout</button>
    </form>
</body>
</html>

Step 5: The Result

Now, you have created a basic Laravel login and register system in Laravel. Users can register, login, access the dashboard, and logout as shown in the following image:

Laravel Login and Register using manual code
Laravel Login & Register Page Using Manual Coding Laravel

With this guide, you can choose the most suitable method for your project and start building a login feature with Laravel. Happy coding!