📖 Laravel Cơ bản đến Nâng cao - Authentication và Authorization
80 phút

Authentication và Authorization trong Laravel

Laravel Breeze / Jetstream

Cài đặt Laravel Breeze

composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev

Manual Authentication

Login Controller

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.',
    ]);
}

Protecting Routes

// Route middleware
Route::get('/profile', function () {
    // Only authenticated users may access this route...
})->middleware('auth');

// Controller constructor
public function __construct()
{
    $this->middleware('auth');
    $this->middleware('auth')->only(['edit', 'update']);
    $this->middleware('guest')->except(['index', 'show']);
}

Authorization với Gates và Policies

Defining Gates

// In AuthServiceProvider
Gate::define('edit-post', function (User $user, Post $post) {
    return $user->id === $post->user_id;
});

// Usage in controller
if (Gate::allows('edit-post', $post)) {
    // The current user can edit the post...
}

// Or in Blade
@can('edit-post', $post)
    <a href="/posts/{{ $post->id }}/edit">Edit Post</a>
@endcan

Creating Policies

php artisan make:policy PostPolicy --model=Post
class PostPolicy
{
    public function update(User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }

    public function delete(User $user, Post $post)
    {
        return $user->id === $post->user_id;
    }
}

Bài tập thực hành

Hãy triển khai hệ thống authentication cho blog!

📝 Bài tập (1)

  1. Tạo hệ thống đăng nhập và phân quyền cho blog

Bài học "Authentication và Authorization" - Khóa học "Laravel Cơ bản đến Nâng cao"