Laravel Authentication – Beginner’s Guide

Laravel Authentication – Beginner’s Guide

We now have a full CRUD app, but anyone can access it.
Let’s add authentication so only registered users can manage contacts.


Installing Laravel Breeze (Simple Auth Scaffolding)

Laravel offers multiple authentication packages, but Laravel Breeze is the simplest for beginners.
It provides login, registration, and password reset out of the box.

Run:

composer require laravel/breeze --dev

Install Breeze:

php artisan breeze:install

Choose Blade when prompted (since our app uses Blade templates).


Running Migrations for Auth Tables

Authentication requires a users table. Run:

php artisan migrate

Compiling the Frontend Assets

If you have Node.js installed:

npm install
npm run dev

If not, you can still use the pre-built Blade templates without compiling, but styles will be minimal.


Testing the Authentication Pages

Breeze automatically creates:

  • /register → Sign up page
  • /login → Login page
  • /forgot-password → Password reset
  • /dashboard → Example protected page

Visit:

http://your-app.test/register

or

http://127.0.0.1:8000/register

Register a new account — you’ll be redirected to /dashboard.


Protecting Your CRUD Routes

We only want logged-in users to manage contacts.

Open routes/web.php:

use App\Http\Controllers\ContactController;

Route::middleware('auth')->group(function () {
    Route::resource('contacts', ContactController::class);
});

This ensures that all contacts routes require login.


Redirecting Guests to Login

If a guest tries to visit /contacts, Laravel will automatically redirect them to /login.


Showing User Info & Logout Link

In layouts/main.blade.php (or your main layout), add:

@if(Auth::check())
    <p>Welcome, {{ Auth::user()->name }}!</p>
    <form action="{{ route('logout') }}" method="POST">
        @csrf
        <button type="submit">Logout</button>
    </form>
@else
    <a href="{{ route('login') }}">Login</a> |
    <a href="{{ route('register') }}">Register</a>
@endif

Conclusion:
Now your CRUD app is fully secured with login and registration.
Only authenticated users can create, view, edit, and delete their contacts.

Note: We have created a basic-level project to understand the entire process of Laravel development. Now, we will dive deeper into each topic and apply them through practical development examples.
You can clone this basic-level tutorial from the following repository:
https://github.com/haroonurasheed/basic-level-project