រំលងទៅមាតិកា

កម្ពុជាត្រូវការសន្តិភាព / Cambodia needs peace

3 នាទីអាន 16Laravel
Laravel

Authenticating users in Laravel

In any web application, protecting sensitive data and restricted actions is a top priority. To do this, you must identify who is using your application to decide if they should have access. This guide explores how Laravel handles user authentication, specifically focusing on Session-Based Authentication.

Understanding and Implementing Session Authentication in Laravel

In any web application, protecting sensitive data and restricted actions is a top priority. To do this, you must identify who is using your application to decide if they should have access. This guide explores how Laravel handles user authentication, specifically focusing on Session-Based Authentication.

1. Authentication Theory: Sessions vs. Tokens

There are two primary ways to identify users in web applications:

Session-Based Authentication

  • How it works: Laravel generates a unique Session ID for every visitor. This ID is stored in a secure cookie within the user's browser.
  • The Match: When a user logs in, their User ID is stored inside that session data on the server. Every subsequent request sends the cookie automatically, allowing Laravel to associate the Session ID with the User ID in your database.
  • Best for: Standard HTML front-ends and traditional web apps.

Token-Based Authentication

  • How it works: Instead of a session ID, the server generates a Token after a successful login.
  • The Match: The client (browser or mobile app) must store this token (often in LocalStorage) and manually send it in the header of every single request.
  • Best for: APIs, Mobile Apps, and Single Page Applications (SPAs).

2. Setting Up the Database

Laravel comes out of the box with a User model and the necessary migrations. Before authenticating, you need users in your database.

Run Migrations and Seeders:

php artisan migrate --seed

3. Creating the Login Logic

To authenticate a user, you need a controller to handle the incoming request.

Step 1: Validation

First, ensure the user has provided a valid email and a password.

// app/Http/Controllers/AuthController.php

namespace App\Http\Controllers;

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

class AuthController extends Controller
{
    public function login(Request $request) 
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);
    }
}

Step 2: The Attempt

Use the Auth facade to attempt a login. The attempt method handles the heavy lifting.

// app/Http/Controllers/AuthController.php

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

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

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

4. Working with the Authenticated User

Once a user is logged in, you can easily access their information anywhere.

  • In a Controller:
$user = Auth::user();
  • In a Blade Template:
<h1>Welcome, {{ Auth::user()->name }}</h1>

5. Logging Out

Logging out removes the User ID association from the session data.

// app/Http/Controllers/AuthController.php

public function logout(Request $request)
{
    Auth::logout();
    $request->session()->invalidate();
    $request->session()->regenerateToken();

    return redirect('/');
}

6. Protecting Routes with Middleware

Apply the auth middleware in your routes/web.php file:

// routes/web.php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\AuthController;

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

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

Here's the video discussing this concept in detail:

Conclusion

Session authentication in Laravel is powerful yet simple. By using built-in tools like Auth::attempt() and the auth middleware, you can secure your application effectively.

ចែករំលែកអត្ថបទនេះ

XLinkedIn

© 2026 Hel Mab. រក្សាសិទ្ធិគ្រប់យ៉ាង.

ភ្នំពេញ កម្ពុជា/បង្កើតដោយ Nuxt