Lecture on Implementing Authentication in Laravel (Login, Logout, Register)

Jul 14, 2024

Lecture on Implementing Authentication in Laravel (Login, Logout, Register)

Introduction

  • Discussion on creating login, logout, and register functions in Laravel.

Setting up Controller

  • Open terminal and generate a new controller: php artisan make:controller SessionController
  • Confirmation: a new file SessionController.php created in app/Http/Controllers.

Creating Functions in Controller

  1. index Function
    • Displays form for email and password input.
    • Generates a blade file for the form (index.blade.php) in resources/views/sesi
  2. login Function
    • Authenticates email and password input from the index form.
    • Validate the email and password.
    • If valid, redirect to a success page; if not, return error messages.

Blade File Creation for index

  • Create a Blade file index.blade.php in resources/views/sesi.
  • Extend layout and create a form with the following fields:
    • Email
    • Password
    • Submit Button

Routing Setup

  • Define routes in routes/web.php:
    Route::get('/sesi', 'SessionController@index');
    Route::post('/sesi/login', 'SessionController@login');
    

Handling CSRF

  • Implement CSRF in the form using @csrf directive for security.

Authentication Logic in login Function

  • Capture the request using Request object.
  • Validate inputs:
    • required for email and password.
  • Authentication using Auth::attempt.
  • Redirection on success or failure:
    if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
        return redirect()->intended('dashboard');
    } else {
        return back()->withErrors(['email' => 'Invalid credentials']);
    }
    

Creating User Model Seeder

  • Generate and configure a seeder: php artisan make:seeder UsersTableSeeder
  • Insert mock data (with hashed passwords) in the run method.
    • Use Hash::make for password hashing.

Refreshing Database

  • Run the seeder to populate users table: php artisan db:seed --class=UsersTableSeeder

Validating Register Form

  1. Creating register Function
    • Displays the registration form.
    • Generate register.blade.php in resources/views/sesi.
  2. Creating create Function
    • Handles registration submission.
    • Validates inputs (name, email, password).
    • Check for unique email.
    • Insert validated data into users table.

Abstracting Logic into Blade Components

  • Create a new Blade component for the header.
  • Display header based on user login status.

Additional Functions

  1. logout Function
    • Logs out the user and redirects to login page with a message.
    • Route definition: Route::get('/sesi/logout', 'SessionController@logout');

Summary

  • Implemented login, logout, and register functionalities in Laravel.
  • Used Blade for form rendering and validation.
  • Handled authentication and session management using Laravel's built-in features.