0
0
Laravelframework~5 mins

Why authentication secures applications in Laravel

Choose your learning style9 modes available
Introduction

Authentication helps keep applications safe by making sure only the right people can use certain parts. It checks who you are before letting you in.

When you want users to log in before accessing their personal data.
When you need to protect admin pages from public access.
When you want to track user actions securely.
When you want to offer personalized content based on who is logged in.
When you want to prevent unauthorized changes to your application.
Syntax
Laravel
Auth::attempt(['email' => $email, 'password' => $password]);

// or using middleware in routes
Route::middleware('auth')->group(function () {
    // protected routes here
});
Laravel uses the Auth facade to handle authentication easily.
Middleware 'auth' protects routes by checking if a user is logged in.
Examples
This example tries to log in a user with email and password. If successful, it sends them to the dashboard.
Laravel
<?php
if (Auth::attempt(['email' => $email, 'password' => $password])) {
    // User is authenticated
    return redirect()->intended('dashboard');
} else {
    // Authentication failed
    return back()->withErrors(['email' => 'Invalid credentials']);
}
This route is protected so only authenticated users can access the profile page.
Laravel
Route::middleware('auth')->get('/profile', function () {
    // Only logged-in users can see this
    return view('profile');
});
Sample Program

This simple Laravel setup shows a login form, processes login, and protects the dashboard page so only logged-in users can see it.

Laravel
<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;

// Route to show login form
Route::get('/login', function () {
    return view('login');
});

// Route to handle login form submission
Route::post('/login', function () {
    $credentials = request()->only('email', 'password');
    if (Auth::attempt($credentials)) {
        return redirect()->intended('/dashboard');
    }
    return back()->withErrors(['email' => 'Invalid credentials']);
});

// Protected dashboard route
Route::middleware('auth')->get('/dashboard', function () {
    return 'Welcome to your dashboard, ' . Auth::user()->name;
});
OutputSuccess
Important Notes

Always hash passwords before storing them; Laravel does this automatically.

Use middleware to protect routes instead of checking authentication manually everywhere.

Authentication is the first step to securing your app; combine it with authorization for better control.

Summary

Authentication checks who a user is before allowing access.

Laravel makes authentication simple with Auth facade and middleware.

Protect sensitive parts of your app by requiring users to log in.