Dev to webs {Coding…}

ร บทเรียนฟรีด้านการพัฒนาซอฟต์แวร์ ที่ครอบคลุมเนื้อหาหลากหลาย ตั้งแต่การเขียนโค้ดพื้นฐานไปจนถึงเทคนิคขั้นสูง

บทที่ 2: การลงทะเบียนผู้ใช้และการเข้าสู่ระบบ

🔹 เกริ่นนำ

หลังจากติดตั้ง Laravel Breeze แล้ว ระบบจะสร้างหน้าเว็บและ route สำหรับการลงทะเบียน (Register) และเข้าสู่ระบบ (Login) มาให้โดยอัตโนมัติ โดยใช้ Blade template ที่อ่านง่ายและแก้ไขได้สะดวก

ในบทนี้เราจะเจาะลึกโค้ดเบื้องหลังของฟอร์มลงทะเบียนและเข้าสู่ระบบ พร้อมอธิบายว่า Laravel จัดการกระบวนการยืนยันตัวตนของผู้ใช้อย่างไร ตั้งแต่การรับข้อมูล การตรวจสอบ และการเข้าสู่ระบบสำเร็จ

🔸 Route ที่เกี่ยวข้อง

// routes/web.php

Route::get('/register', [RegisteredUserController::class, 'create']);
Route::post('/register', [RegisteredUserController::class, 'store']);

Route::get('/login', [AuthenticatedSessionController::class, 'create']);
Route::post('/login', [AuthenticatedSessionController::class, 'store']);

🔸 ตัวอย่าง Blade Template (resources/views/auth/register.blade.php)

<form method="POST" action="{{ route('register') }}">
    @csrf
    <input type="text" name="name" placeholder="Name">
    <input type="email" name="email" placeholder="Email">
    <input type="password" name="password" placeholder="Password">
    <input type="password" name="password_confirmation" placeholder="Confirm Password">
    <button type="submit">Register</button>
</form>

🔸 การใช้งาน Auth

use Illuminate\Support\Facades\Auth;

// เข้าสู่ระบบ
Auth::attempt(['email' => $email, 'password' => $password]);

// ตรวจสอบว่าผู้ใช้ login อยู่หรือไม่
Auth::check();

// เข้าถึงข้อมูลผู้ใช้
$user = Auth::user();

// ออกจากระบบ
Auth::logout();

💡 Laravel จะสร้าง session และ redirect ผู้ใช้อัตโนมัติหลังเข้าสู่ระบบสำเร็จ