Laravel 12 Authentication & Authorization: A Beginner’s Guide (With Examples)

Author

Kritim Yantra

Mar 27, 2025

Laravel 12 Authentication & Authorization: A Beginner’s Guide (With Examples)

Authentication (who you are) and Authorization (what you can do) are essential for securing web applications. Laravel makes it incredibly easy to implement both.

In this guide, we’ll cover:
Authentication Setup (Login, Register, Password Reset)
Authorization (Gates, Policies, Middleware)
Role-Based Access Control (RBAC)
Best Practices for Security

Let’s get started!


1. What is Authentication?

Authentication verifies who a user is. Examples:

  • Login/Logout
  • Registration
  • Password Reset

Laravel provides built-in scaffolding for authentication.


2. Setting Up Authentication in Laravel 12

Step 1: Install Laravel & Set Up Database

composer create-project laravel/laravel laravel-auth
cd laravel-auth

Configure .env with your database:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_auth
DB_USERNAME=root
DB_PASSWORD=

Run migrations:

php artisan migrate

Step 2: Install Laravel Breeze (Simple Auth Scaffolding)

Laravel Breeze provides login, registration, and password reset out of the box.

composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev
php artisan migrate

Now visit:
🔗 http://localhost:8000/register (Registration)
🔗 http://localhost:8000/login (Login)

You now have a fully working auth system!


3. How Laravel Handles Authentication?

Laravel uses:

  • Sessions (default for web)
  • API Tokens (for APIs, using Sanctum)

Manually Authenticating a User

Example: Custom login logic in LoginController:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

public function login(Request $request)
{
    $credentials = $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    if (Auth::attempt($credentials)) {
        return redirect('/dashboard'); // Login success
    }

    return back()->withErrors(['email' => 'Invalid credentials']); // Login failed
}

Checking if a User is Logged In

@if (Auth::check())
    <p>Welcome, {{ Auth::user()->name }}!</p>
@endif

Logging Out

Auth::logout();
return redirect('/');

4. What is Authorization?

Authorization controls what a user can do. Examples:

  • Can a user edit a post?
  • Is this user an admin?

Laravel provides Gates and Policies for authorization.


5. Authorization Using Gates

Gates are Closure-based checks (good for simple rules).

Example: Allow Only Admins to Access a Page

Step 1: Define a Gate (in App\Providers\AuthServiceProvider)

use Illuminate\Support\Facades\Gate;

public function boot()
{
    Gate::define('access-admin', function ($user) {
        return $user->is_admin; // Checks if user is admin
    });
}

Step 2: Use the Gate in a Controller

public function adminDashboard()
{
    if (Gate::allows('access-admin')) {
        return view('admin.dashboard');
    }
    abort(403, 'Unauthorized!');
}

Step 3: Protect Routes with Middleware

Route::get('/admin', function () {
    // Only admins can access
})->middleware('can:access-admin');

6. Authorization Using Policies

Policies are class-based and useful for model-specific permissions.

Example: Check if a User Can Edit a Post

Step 1: Generate a Policy

php artisan make:policy PostPolicy --model=Post

Step 2: Define Rules in PostPolicy.php

public function update(User $user, Post $post)
{
    return $user->id === $post->user_id; // Only post owner can edit
}

Step 3: Use the Policy in a Controller

public function edit(Post $post)
{
    $this->authorize('update', $post); // Checks policy
    return view('posts.edit', compact('post'));
}

Step 4: Protect Routes

Route::put('/posts/{post}', [PostController::class, 'update'])
    ->middleware('can:update,post');

7. Role-Based Access Control (RBAC)

For complex apps, use roles (Admin, Editor, User).

Step 1: Add role Column to Users

php artisan make:migration add_role_to_users_table --table=users
public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->enum('role', ['admin', 'editor', 'user'])->default('user');
    });
}

Run migration:

php artisan migrate

Step 2: Create Middleware for Roles

php artisan make:middleware CheckAdmin

Edit app/Http/Middleware/CheckAdmin.php:

public function handle($request, Closure $next)
{
    if (Auth::check() && Auth::user()->role === 'admin') {
        return $next($request);
    }
    abort(403, 'Access Denied!');
}

Step 3: Protect Routes

Route::get('/admin', function () {
    return view('admin.dashboard');
})->middleware('auth', 'checkadmin');

8. Best Practices for Secure Authentication

Use HTTPS to prevent data interception.
Hash passwords (Laravel does this automatically).
Limit login attempts (use ThrottleRequests middleware).
Sanitize user input to prevent SQL injection.
Use @csrf in forms to prevent CSRF attacks.


Conclusion

Authentication = Who are you? (Login/Register)
Authorization = What can you do? (Gates/Policies)
RBAC = Control access via roles (Admin, User)

🚀 Now go ahead and secure your Laravel app!

Tags

Laravel Php

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Continue with Google

Related Posts