What is Auth? How is it used?

Photo by Ed Hardie on Unsplash

What is Auth? How is it used?

"Auth" refers to the authentication system provided by the framework to manage user authentication, including user login, registration, password reset, and session management.

The "Auth" system in Laravel is based on guards and providers. Here’s a breakdown of how it's used:

  1. Configuration: Laravel's authentication system is configured primarily in the config/auth.php file. This file defines various settings related to authentication, including different "guards" and "providers".

  2. Guards: Guards define how users are authenticated for each request. Laravel ships with several guard implementations, including session and token guards. The session guard, for example, maintains user authentication state using session storage.

  3. Providers: Providers define how users are retrieved from your persistent storage (such as a database). Laravel supports various types of authentication providers, such as Eloquent (for database-based authentication using the ORM) and LDAP (for LDAP authentication).

  4. Usage: To use the authentication system in your application, you typically interact with it through the Auth facade provided by Laravel. Here are some common operations:

    • User Authentication: To authenticate a user, you can use:

        if (Auth::attempt(['email' => $email, 'password' => $password])) {
            // Authentication was successful
        }
      
    • Checking Authentication: To check if a user is authenticated:

        if (Auth::check()) {
            // User is authenticated
        }
      
    • Getting the Authenticated User: To retrieve the currently authenticated user:

        $user = Auth::user();
      
    • Logging Users Out: To log out a user:

        Auth::logout();
      
    • Protecting Routes: Laravel provides route middleware to protect routes from unauthenticated access. You can apply middleware like auth to routes or controllers to enforce authentication:

        Route::get('/profile', 'ProfileController@show')->middleware('auth');
      
  5. Customization: Laravel’s authentication system can be customized extensively to fit your application's needs. You can define custom guards and providers in the configuration file (config/auth.php) and extend the existing authentication controllers and services.