Mahamudul Hasan Rubel
HomeBlogCoursesAboutProjectsSkillsExperiencePhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • Blog
  • Courses
  • About
  • Projects
  • Skills
  • Experience
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

Back to Blog
Lesson 7 of the Intermediate Laravel: Real-World Application Patterns course
LaravelJune 25, 20263 min read

Mastering REST API Authentication with Laravel Sanctum

Learn to secure your Laravel API using Sanctum. We'll cover installation, route configuration, and token generation to authenticate your users effectively.

LaravelAPISanctumAuthenticationPHPbackend

Previously in this course, we explored service-oriented task management to keep our business logic clean and decoupled. Now that our core application logic is structured, it is time to expose that functionality via a secure interface. In this lesson, we will implement token-based authentication using Laravel Sanctum, transforming our application into a robust API.

Understanding API Authentication with Sanctum

When building a stateless API, traditional session-based authentication (which relies on cookies) is often insufficient, especially for mobile apps or third-party integrations. Laravel Sanctum provides a lightweight authentication system that allows you to issue API tokens to users.

Sanctum works by attaching a token to the Authorization header of an incoming request. When the server receives a request, the auth:sanctum middleware intercepts it, verifies the token against the personal_access_tokens table, and identifies the authenticated user.

Installing and Configuring Sanctum

First, install Sanctum via Composer:

Bash
composer require laravel/sanctum

Next, publish the configuration file and run the migrations to create the necessary database tables:

Bash
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

Finally, ensure the HasApiTokens trait is added to your User model. This trait provides the methods necessary to issue tokens and verify abilities:

PHP
namespace App\Models;

use Laravel\Sanctum\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}

Implementing Token Generation

To allow users to authenticate, we need an endpoint that accepts credentials and returns a plain-text token. In a production environment, you would typically handle this in an AuthController.

Here is a concrete example of how to generate a token:

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

    $user = User::where('email', $request->email)->first();

    if (! $user || ! Hash::check($request->password, $user->password)) {
        throw ValidationException::withMessages([
            'email' => ['The provided credentials are incorrect.'],
        ]);
    }

    #6A9955">// Generate the token
    $token = $user->createToken($request->device_name)->plainTextToken;

    return response()->json(['token' => $token], 200);
}

The createToken method returns a NewAccessToken instance. The plainTextToken property is the only time you will see the full token; ensure you return this to the client, as you cannot retrieve it again later.

Configuring API Routes

With the authentication logic in place, we need to protect our routes. Open routes/api.php. Sanctum automatically registers the auth:sanctum middleware, which you can apply to your routes to ensure only authenticated users can access them.

PHP
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/user', function (Request $request) {
        return $request->user();
    });

    Route::apiResource('tasks', TaskController::class);
});

By grouping these routes, any request missing a valid Authorization: Bearer {token} header will receive a 401 Unauthorized response.

Hands-on Exercise

  1. Create a LoginController if you haven't already.
  2. Implement the login method shown above.
  3. Use Postman or curl to send a POST request to your login endpoint.
  4. Take the returned token and use it to access the /api/user endpoint by adding the header: Authorization: Bearer YOUR_TOKEN_HERE.

Common Pitfalls

  • Forgetting the Trait: If you forget to add HasApiTokens to your User model, the createToken method will not exist, leading to a "method not found" error.
  • Returning the Token Object: Never return the entire $token object from your controller. It contains metadata that should not be exposed. Always return the plainTextToken string.
  • Header Mismatch: Always ensure your client is sending the header as Authorization: Bearer {token}. A common mistake is omitting the Bearer prefix.
  • Database Migrations: If you installed Sanctum after your initial database setup, ensure you actually ran php artisan migrate. Without the personal_access_tokens table, authentication will fail silently or throw a query exception.

Recap

We have successfully integrated Sanctum into our project. We installed the package, prepared our User model, implemented a token generation flow, and secured our API routes using middleware. This foundation allows us to move forward with building sophisticated API resources that are both secure and easy to maintain.

Up next: We will explore Resource Controllers and API Responses to ensure our data is transformed consistently before it reaches the client.

Previous lessonService-Oriented Task ManagementNext lesson Resource Controllers and API Responses
Back to Blog

Similar Posts

LaravelJune 25, 20263 min read

Testing Forms and Validation in Laravel: A Practical Guide

Stop manually testing your forms. Learn how to use Laravel's testing suite to automate validation checks, simulate authenticated users, and ensure data integrity.

Read more
LaravelJune 25, 20263 min read

Resource Controllers and API Responses in Laravel

Learn how to use Laravel API resources to transform model data and return consistent, clean JSON responses for your RESTful applications.

Part of the course

Intermediate Laravel: Real-World Application Patterns

intermediate · Lesson 7 of 58

  1. 1

    Architecting for Maintainability

    3 min
  2. 2

    Implementing the Service Layer

    3 min
  3. 3

    Repository Pattern Fundamentals

    3 min
Read more
LaravelJune 25, 20263 min read

Task Manager: Refactoring for Clean Code

Learn to refactor your Task Manager by moving business logic into Service classes, cleaning up controllers, and simplifying your Blade templates.

Read more
  • 4

    Project Board Domain Modeling

    3 min
  • 5

    Advanced Eloquent Scopes and Accessors

    4 min
  • 6

    Service-Oriented Task Management

    3 min
  • 7

    REST API Fundamentals with Sanctum

    3 min
  • 8

    Resource Controllers and API Responses

    3 min
  • 9

    Handling API Validation and Form Requests

    3 min
  • 10

    Implementing Middleware for API Security

    Coming soon
  • 11

    Database Transactions for Data Integrity

    Coming soon
  • 12

    Error Handling and Global Exceptions

    Coming soon
  • 13

    Introduction to Laravel Events and Listeners

    Coming soon
  • 14

    Asynchronous Processing with Queues

    Coming soon
  • 15

    Job Chaining and Batching

    Coming soon
  • 16

    Feature Testing Fundamentals

    Coming soon
  • 17

    Mocking Services and Repositories in Tests

    Coming soon
  • 18

    Testing Events and Jobs

    Coming soon
  • 19

    Database Factories and Seeding

    Coming soon
  • 20

    API Versioning Strategies

    Coming soon
  • 21

    Advanced Request Filtering and Sorting

    Coming soon
  • 22

    Handling File Uploads in REST APIs

    Coming soon
  • 23

    Real-time Notifications with Broadcasting

    Coming soon
  • 24

    Using Observers for Model Lifecycle Hooks

    Coming soon
  • 25

    Implementing Policies for Authorization

    Coming soon
  • 26

    Customizing Authentication Guards

    Coming soon
  • 27

    Rate Limiting API Endpoints

    Coming soon
  • 28

    Eloquent Performance Optimization

    Coming soon
  • 29

    Caching Strategies for Performance

    Coming soon
  • 30

    Using Traits for Code Reuse

    Coming soon
  • 31

    Advanced Dependency Injection with Service Providers

    Coming soon
  • 32

    Command Line Tools with Artisan

    Coming soon
  • 33

    Scheduled Tasks and Cron Jobs

    Coming soon
  • 34

    Integrating Third-Party Services

    Coming soon
  • 35

    Handling Webhooks

    Coming soon
  • 36

    Logging and Monitoring

    Coming soon
  • 37

    Database Migrations Best Practices

    Coming soon
  • 38

    Advanced Testing: Integration Tests

    Coming soon
  • 39

    Testing API Authentication

    Coming soon
  • 40

    Code Quality and Static Analysis

    Coming soon
  • 41

    Project Structure for Large Applications

    Coming soon
  • 42

    Environment and Configuration Management

    Coming soon
  • 43

    Deploying Laravel Applications

    Coming soon
  • 44

    Database Indexing Strategies

    Coming soon
  • 45

    Using Value Objects

    Coming soon
  • 46

    Strategy Pattern for Business Rules

    Coming soon
  • 47

    Advanced Queue Monitoring

    Coming soon
  • 48

    Building a Search API

    Coming soon
  • 49

    Handling Concurrency and Race Conditions

    Coming soon
  • 50

    API Documentation with OpenAPI

    Coming soon
  • 51

    Testing with Test Doubles

    Coming soon
  • 52

    Implementing Multi-Tenancy

    Coming soon
  • 53

    Refactoring Legacy Code

    Coming soon
  • 54

    Using Middleware for Feature Flags

    Coming soon
  • 55

    Building Reusable Packages

    Coming soon
  • 56

    Performance Profiling

    Coming soon
  • 57

    Secure API Design

    Coming soon
  • 58

    Event Sourcing Concepts

    Coming soon
  • View full course