Trong quá trình phát triển ứng dụng web với Laravel, một trong những tính năng cơ bản nhất là đăng nhậpđăng ký người dùng. Mặc dù Laravel đã cung cấp sẵn các chức năng này thông qua package Laravel Breeze hoặc Laravel Jetstream, nhưng đôi khi bạn cần tạo một hệ thống đăng nhập và đăng ký tuỳ chỉnh để đáp ứng các yêu cầu cụ thể của ứng dụng.

Trong bài viết này thuộc series "Học Laravel" của codetuthub.com, chúng ta sẽ cùng nhau xây dựng một hệ thống custom user login và registration trong Laravel 11 mà không phụ thuộc vào các package như Breeze hay Jetstream. Bài viết này sẽ hướng dẫn bạn từng bước từ thiết lập cơ bản đến hoàn thiện chức năng.

1. Cài đặt dự án Laravel 11

Trước tiên, bạn cần cài đặt một dự án Laravel mới hoặc sử dụng dự án có sẵn. Để cài đặt Laravel 11, bạn cần đảm bảo rằng máy tính của bạn đã cài đặt Composer.

Bước 1: Tạo một dự án Laravel mới

Mở terminal và chạy lệnh sau để tạo một dự án Laravel mới:

shell
composer create-project laravel/laravel laravel-custom-auth

Sau khi cài đặt thành công, di chuyển vào thư mục dự án:

shell
cd laravel-custom-auth

Tiếp theo, bạn cần cấu hình file .env để kết nối với cơ sở dữ liệu. Đảm bảo rằng bạn đã thiết lập cấu hình cơ sở dữ liệu chính xác.

Bước 2: Tạo cơ sở dữ liệu và chạy migrate

Tạo một cơ sở dữ liệu trong MySQL và sau đó cập nhật thông tin kết nối trong file .env:

shell
.env
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password

Chạy lệnh migrate để tạo các bảng mặc định của Laravel, bao gồm bảng users:

shell
php artisan migrate

2. Tạo Routes cho các trang Đăng Nhập và Đăng Ký

Trong Laravel, các route được định nghĩa trong file routes/web.php. Chúng ta sẽ thêm các route để hiển thị form đăng ký và đăng nhập, cũng như xử lý logic cho các chức năng này.

Mở file routes/web.php và thêm các route sau:

php
routes/web.php
use App\Http\Controllers\AuthController;
use Illuminate\Support\Facades\Route;

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

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

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

3. Tạo AuthController

Chúng ta sẽ tạo một controller để xử lý logic đăng nhập, đăng ký, và đăng xuất. Sử dụng lệnh Artisan để tạo AuthController:

shell
php artisan make:controller AuthController

Mở file app/Http/Controllers/AuthController.php và cập nhật như sau:

php
app/Http/Controllers/AuthController.php
namespace App\Http\Controllers;

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

class AuthController extends Controller
{
    // Hiển thị form đăng ký
    public function showRegistrationForm()
    {
        return view('auth.register');
    }

    // Xử lý đăng ký người dùng
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);

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

        return redirect()->route('login')->with('success', 'Đăng ký thành công. Bạn có thể đăng nhập.');
    }

    // Hiển thị form đăng nhập
    public function showLoginForm()
    {
        return view('auth.login');
    }

    // Xử lý đăng nhập
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
        ]);

        if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
            $request->session()->regenerate();
            return redirect()->intended('dashboard')->with('success', 'Đăng nhập thành công.');
        }

        throw ValidationException::withMessages([
            'email' => 'Thông tin đăng nhập không chính xác.',
        ]);
    }

    // Xử lý đăng xuất
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/login')->with('success', 'Bạn đã đăng xuất.');
    }
}

Giải thích:

  • showRegistrationForm(): Hiển thị form đăng ký người dùng.
  • register(): Xử lý logic đăng ký, bao gồm xác thực dữ liệu và lưu người dùng vào cơ sở dữ liệu.
  • showLoginForm(): Hiển thị form đăng nhập.
  • login(): Xử lý đăng nhập, kiểm tra email và mật khẩu có hợp lệ hay không.
  • logout(): Đăng xuất người dùng và hủy bỏ session.

4. Tạo Views cho các trang Đăng Nhập và Đăng Ký

Tiếp theo, chúng ta sẽ tạo các file view cho form đăng nhập và đăng ký. Trong thư mục resources/views, tạo một thư mục con tên là auth. Sau đó, tạo hai file login.blade.phpregister.blade.php bên trong thư mục này.

4.1. login.blade.php

php
login.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Đăng Nhập</title>
</head>
<body>
    <h2>Đăng Nhập</h2>

    @if(session('success'))
        <div>{{ session('success') }}</div>
    @endif

    <form method="POST" action="{{ route('login') }}">
        @csrf
        <div>
            <label>Email:</label>
            <input type="email" name="email" value="{{ old('email') }}">
            @error('email')
                <span>{{ $message }}</span>
            @enderror
        </div>

        <div>
            <label>Mật khẩu:</label>
            <input type="password" name="password">
            @error('password')
                <span>{{ $message }}</span>
            @enderror
        </div>

        <button type="submit">Đăng Nhập</button>
    </form>
</body>
</html>

4.2. register.blade.php

php
register.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Đăng Ký</title>
</head>
<body>
    <h2>Đăng Ký</h2>

    @if(session('success'))
        <div>{{ session('success') }}</div>
    @endif

    <form method="POST" action="{{ route('register') }}">
        @csrf
        <div>
            <label>Tên:</label>
            <input type="text" name="name" value="{{ old('name') }}">
            @error('name')
                <span>{{ $message }}</span>
            @enderror
        </div>

        <div>
            <label>Email:</label>
            <input type="email" name="email" value="{{ old('email') }}">
            @error('email')
                <span>{{ $message }}</span>
            @enderror
        </div>

        <div>
            <label>Mật khẩu:</label>
            <input type="password" name="password">
            @error('password')
                <span>{{ $message }}</span>
            @enderror
        </div>

        <div>
            <label>Nhập lại mật khẩu:</label>
            <input type="password" name="password_confirmation">
        </div>

        <button type="submit">Đăng Ký</button>
    </form>
</body>
</html>

5. Trang Dashboard và điều hướng sau khi đăng nhập thành công

Sau khi người dùng đăng nhập thành công, bạn muốn điều hướng họ đến một trang chỉ dành cho người đã đăng nhập, ví dụ như trang dashboard. Để làm điều này, hãy tạo route và view cho trang dashboard.

Bước 1: Thêm route cho trang Dashboard

Mở file routes/web.php và thêm route sau:

php
routes/web.php
Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware('auth')->name('dashboard');

Bước 2: Tạo view dashboard.blade.php

Tạo file resources/views/dashboard.blade.php:

php
resources/views/dashboard.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Dashboard</title>
</head>
<body>
    <h2>Chào mừng đến với Dashboard!</h2>

    <form method="POST" action="{{ route('logout') }}">
        @csrf
        <button type="submit">Đăng Xuất</button>
    </form>
</body>
</html>

6. Kiểm tra và hoàn thiện

Bây giờ bạn có thể khởi động server bằng lệnh:

shell
php artisan serve

Truy cập vào http://localhost:8000/register để đăng ký và http://localhost:8000/login để đăng nhập. Sau khi đăng nhập thành công, người dùng sẽ được chuyển hướng đến trang dashboard.

Kết luận

Trong bài viết này, chúng ta đã tạo thành công hệ thống Custom User Login và Registration trong Laravel 11. Bạn đã học cách tạo các route, controller, form đăng ký và đăng nhập, cũng như cách xử lý đăng xuất và bảo vệ trang bằng middleware. Hy vọng rằng bài viết này sẽ giúp ích cho bạn trong quá trình phát triển ứng dụng Laravel.

Hãy tiếp tục theo dõi codetuthub.com để khám phá thêm nhiều kiến thức thú vị về Laravel và các công nghệ lập trình khác!