laravel-autenticacion-en-laravel

Authentication in Laravel

  • 2 min

Authentication is the process of verifying the identity of someone trying to access an application.

The official starter kits include the routes, actions, and screens needed for registration, login, password recovery, and email verification. They all rely on Laravel Fortify for the authentication logic.

Create the project with authentication

Choose the starter kit during the creation of a new application. If you don’t have the installer yet, add it with Composer:

composer global require laravel/installer
laravel new mi-super-app
Copied!

The wizard will ask you which interface you want to use. Choose Livewire if you prefer to stay close to Blade and PHP, or React, Vue, or Svelte if you want a JavaScript interface. Then install the resources and start the environment:

cd mi-super-app
npm install && npm run build
composer run dev
Copied!

The starter kit already includes the migrations and the authentication code within the project, so you can modify it. If the database has not been migrated during installation, run:

php artisan migrate
Copied!

Available functions

According to the options enabled in config/fortify.php, you will have routes for login, registration, logout, password recovery, email verification, and two-step authentication. You can check them with:

php artisan route:list
Copied!

Protect routes with middleware

Now that you have users, you will want certain pages (like /secret-panel or /create-product) to be visible only to logged-in people.

In Laravel, this is done with Middleware. It is a “security guard” placed at the door of the route.

In routes/web.php:

// Public route (anyone can enter)
Route::get('/', function () {
    return view('welcome');
});

// Protected route (only logged-in users)
Route::get('/panel', function () {
    return view('panel_secreto');
})->middleware(['auth']); // <--- THE SECURITY GUARD
Copied!

If a non-logged-in user tries to access /panel, Laravel detects it and automatically redirects them to Login.

Access the authenticated user

How do you know who is visiting the website to say “Hello, Juan”? Laravel offers a global “helper” called auth().

In the Controller or PHP:

$usuario = auth()->user();
echo $usuario->name;  // "Juan"
echo $usuario->email; // "[email protected]"
echo $usuario->id;    // 1
Copied!

In the View (Blade):

@auth
    <p>Welcome, {{ auth()->user()->name }}</p>
    <form action="{{ route('logout') }}" method="POST">
        @csrf
        <button type="submit">Logout</button>
    </form>
@endauth

@guest
    <p>Hello guest, please <a href="/login">log in</a>.</p>
@endguest
Copied!