Laravel Authentication
Authentication in Laravel is a feature that manages user authentication and authorization, allowing users to log in, register, and manage their sessions securely. Laravel provides a robust authentication system out of the box, which includes functionality for user login, registration, password resets, and more.
Key Components of Laravel Authentication
Authentication Scaffolding: Laravel offers built-in authentication scaffolding that sets up basic authentication features for your application. You can use Laravel Breeze or Laravel Jetstream for this purpose.
Laravel Breeze: Laravel Breeze provides a simple and minimal authentication system, including login, registration, and password reset functionality.
- Install Laravel Breeze:
composer require laravel/breeze --dev php artisan breeze:install npm install && npm run dev php artisan migrate
- Install Laravel Breeze:
Laravel Jetstream: Laravel Jetstream is a more advanced authentication system that includes additional features such as two-factor authentication, session management, and team management.
- Install Laravel Jetstream:
composer require laravel/jetstream php artisan jetstream:install livewire npm install && npm run dev php artisan migrate
- Install Laravel Jetstream:
Authentication Configuration: Laravel's authentication configuration is located in the
config/auth.php
file. This file defines various settings related to authentication, including:Default Guard: Defines the default authentication guard used by the application.
'defaults' => [ 'guard' => 'web', 'passwords' => 'users', ],
Guards: Define the guards that handle user authentication. The default guard is typically
web
, but you can define additional guards for APIs or other use cases.'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', ], ],
Providers: Define how user data is retrieved from storage. The default provider is
users
, which typically uses theusers
table.'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\User::class, ], ],
User Model: The
User
model, located atapp/Models/User.php
, represents the users of your application. This model typically uses theAuthenticatable
trait, which provides methods for user authentication.Example:
namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Notifications\Notifiable; class User extends Authenticatable { use Notifiable; protected $fillable = [ 'name', 'email', 'password', ]; protected $hidden = [ 'password', 'remember_token', ]; }
Authentication Routes: Laravel provides predefined routes for authentication, including login, registration, and password resets. These routes are included when using Laravel Breeze or Jetstream.
- Authentication Routes Example:
Route::get('login', [LoginController::class, 'showLoginForm'])->name('login'); Route::post('login', [LoginController::class, 'login']); Route::post('logout', [LoginController::class, 'logout'])->name('logout'); Route::get('register', [RegisterController::class, 'showRegistrationForm'])->name('register'); Route::post('register', [RegisterController::class, 'register']); Route::get('password/reset', [ForgotPasswordController::class, 'showLinkRequestForm'])->name('password.request'); Route::post('password/email', [ForgotPasswordController::class, 'sendResetLinkEmail'])->name('password.email'); Route::get('password/reset/{token}', [ResetPasswordController::class, 'showResetForm'])->name('password.reset'); Route::post('password/reset', [ResetPasswordController::class, 'reset'])->name('password.update');
- Authentication Routes Example:
Authentication Controllers: Controllers handle authentication logic. Laravel Breeze and Jetstream provide controllers for login, registration, and password reset.
- Example Authentication Controller:
namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class LoginController extends Controller { public function showLoginForm() { return view('auth.login'); } public function login(Request $request) { $credentials = $request->only('email', 'password'); if (Auth::attempt($credentials)) { return redirect()->intended('dashboard'); } return back()->withErrors([ 'email' => 'The provided credentials do not match our records.', ]); } public function logout(Request $request) { Auth::logout(); return redirect('/'); } }
- Example Authentication Controller:
Middleware for Authentication: Laravel uses middleware to handle authentication checks. The
auth
middleware ensures that users are authenticated before accessing certain routes.- Apply Middleware to Routes:
Route::get('dashboard', [DashboardController::class, 'index'])->middleware('auth');
- Apply Middleware to Routes:
Password Reset: Laravel provides built-in functionality for resetting user passwords. Users can request a password reset link, and Laravel handles the process of sending the link and updating the password.
- Password Reset Workflow:
- Request a password reset link.
- Send the reset link to the user's email.
- User clicks the link and is directed to a password reset form.
- User submits the form with a new password, which is updated in the database.
- Password Reset Workflow:
Two-Factor Authentication: Laravel Jetstream supports two-factor authentication, adding an extra layer of security. It requires users to provide a second form of verification, such as a code sent to their mobile device.
- Enable Two-Factor Authentication: Laravel Jetstream handles two-factor authentication setup and verification out of the box.
Social Authentication: Laravel provides support for social authentication via packages like Laravel Socialite, allowing users to authenticate using social media accounts such as Google, Facebook, or GitHub.
Install Laravel Socialite:
composer require laravel/socialite
Configure Socialite: Add social provider credentials to the
config/services.php
file.Socialite Example:
use Laravel\Socialite\Facades\Socialite; public function redirectToProvider() { return Socialite::driver('google')->redirect(); } public function handleProviderCallback() { $user = Socialite::driver('google')->user(); // Handle the user information }
Summary
Authentication in Laravel manages user access and security with the following features:
- Authentication Scaffolding: Use Laravel Breeze or Jetstream for pre-built authentication features.
- Authentication Configuration: Configure guards, providers, and other settings in
config/auth.php
. - User Model: Represents users and handles authentication-related methods.
- Authentication Routes: Predefined routes for login, registration, and password resets.
- Authentication Controllers: Handle the logic for authentication processes.
- Middleware: Protect routes with authentication middleware.
- Password Reset: Built-in functionality for resetting passwords.
- Two-Factor Authentication: Supported by Laravel Jetstream for enhanced security.
- Social Authentication: Integrate with social media accounts using Laravel Socialite.
Laravel's authentication system provides a comprehensive and flexible solution for managing user authentication and authorization, making it easier to secure and manage user access in your application.