PHPackages                             martin6363/laravel-api-auth - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. martin6363/laravel-api-auth

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

martin6363/laravel-api-auth
===========================

Professional, configuration-driven API authentication package for Laravel 12+ using Sanctum

v1.4.1(3mo ago)13MITPHPPHP ^8.2

Since Jan 13Pushed 3mo agoCompare

[ Source](https://github.com/Martin6363/laravel-api-auth)[ Packagist](https://packagist.org/packages/martin6363/laravel-api-auth)[ RSS](/packages/martin6363-laravel-api-auth/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (6)Versions (8)Used By (0)

Laravel API Auth
================

[](#laravel-api-auth)

[![Latest Version on Packagist](https://camo.githubusercontent.com/2edb3305ac102c087dd04794f641fb40fabce9457dd9607d4b22b9d19650a35d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d617274696e363336332f6c61726176656c2d6170692d617574682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/martin6363/laravel-api-auth)[![Total Downloads](https://camo.githubusercontent.com/2fbed83215cba8abd356f5655966a92578c452ef9537663d4754bf214e6fa775/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d617274696e363336332f6c61726176656c2d6170692d617574682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/martin6363/laravel-api-auth)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![License](https://camo.githubusercontent.com/695cd9e682c8206c29b16aa4f7a555b1ee9f9d045b90469a8647b43661231652/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d617274696e363336332f6c61726176656c2d6170692d617574682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/martin6363/laravel-api-auth)

A professional, configuration-driven API authentication package for Laravel 11 &amp; 12+ using Laravel Sanctum. Built with clean architecture principles and designed for easy customization.

✨ Features
----------

[](#-features)

- 🔐 **Complete Authentication Flow**: Registration, Login, Logout
- 🆔 **Dynamic Identification**: Login using email, username, or any custom field
- 🔑 **Token Management**: Access tokens with refresh capability
- 🔒 **Password Management**: Forgot password and reset password functionality
- ✉️ **Email Verification**: Built-in email verification support (Queueable &amp; Customizable)
- 👤 **User Profile**: Get authenticated user profile endpoint
- 🛡️ **Rate Limiting**: Configurable rate limiting for security
- ⚙️ **Highly Configurable**: Extensive configuration options
- 🏗️ **Clean Architecture**: Service-oriented design for easy extension
- 🧪 **Test Ready**: Built with testing in mind

📋 Requirements
--------------

[](#-requirements)

- PHP &gt;= 8.2+
- Laravel &gt;= 11.0 or &gt;= 12.0
- Laravel Sanctum &gt;= 4.0

🚀 Installation
--------------

[](#-installation)

### Step 1: Install via Composer

[](#step-1-install-via-composer)

```
composer require martin6363/laravel-api-auth
```

### Step 2: Install Laravel Sanctum (if not already installed)

[](#step-2-install-laravel-sanctum-if-not-already-installed)

```
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
```

### Step 3: Install the Package

[](#step-3-install-the-package)

```
php artisan api-auth:install  # --force will update the existing config file
```

This command will:

- Publish the configuration file to `config/api-auth.php`
- Check for Laravel Sanctum installation
- Optionally run migrations

### 🗑️ &gt; Uninstallation

[](#️--uninstallation)

If you need to remove the package and all its published components (config, controllers, services, etc.), run:

```
php artisan api-auth:uninstall
```

### Step 4 (Optional): Publish Logics (Controllers, Services)

[](#step-4-optional-publish-logics-controllers-services)

- If you want to customize the internal logic of the authentication (e.g., change the registration logic or add custom responses), you can publish the controllers, services to your application:

```
php artisan vendor:publish --tag=api-auth-logic
```

### Step 5: Configure Your User Model

[](#step-5-configure-your-user-model)

Ensure your `User` model uses the `HasApiTokens` trait from Laravel Sanctum:

```
use Laravel\Sanctum\HasApiTokens;

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

### Step 6: Configure Email (Optional)

[](#step-6-configure-email-optional)

If you're using email verification or password reset, configure your email settings in `.env`:

```
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=noreply@example.com
MAIL_FROM_NAME="${APP_NAME}"
```

⚙️ Configuration
----------------

[](#️-configuration)

After installation, you can customize the package behavior by editing `config/api-auth.php`:

### User Model

[](#user-model)

```
'user_model' => \App\Models\User::class,
```

### Token Configuration

[](#token-configuration)

```
'token' => [
    'name' => 'auth_token',           // Token name
    'abilities' => ['*'],             // Token abilities
    'expires_at' => null,            // Token expiration (null = no expiration)
],
```

### Route Configuration

[](#route-configuration)

```
'routes' => [
    'prefix' => 'api/auth',           // Route prefix
    'middleware' => ['api'],          // Route middleware
    'enabled' => [
        'register' => true,
        'login' => true,
        'logout' => true,
        'forgot_password' => true,
        'reset_password' => true,
        'email_verification' => true,
        'profile' => true,
        'refresh_token' => true,
    ],
],
```

### Email Verification

[](#email-verification)

```
'email_verification' => [
    'required' => false,              // Require verification on registration
    'send_on_register' => true,       // Auto-send verification email
],
```

### Email Theme Customization

[](#email-theme-customization)

- Customize the look and feel of your verification emails directly from the config.

```
'emails' => [
    'dispatch_mode' => 'queue', // 'queue' or 'sync'
    'theme' => [
        'primary_color' => '#4f46e5',
        'button_text_color' => '#ffffff',
    ],
],
```

### Password Configuration

[](#password-configuration)

```
'password' => [
    'min_length' => 8,                // Minimum password length
    'require_confirmation' => true,    // Require password confirmation
    'reset_token_expires' => 60,       // Reset token expiration (minutes)
],
```

### Rate Limiting

[](#rate-limiting)

```
'rate_limiting' => [
    'enabled' => true,                 // Enable rate limiting
    'max_attempts' => 5,               // Max attempts per minute (login/register)
    'password_reset_max_attempts' => 3, // Max attempts for password reset
],
```

📡 API Endpoints
---------------

[](#-api-endpoints)

### Public Endpoints

[](#public-endpoints)

#### Register

[](#register)

```
POST /api/auth/register
Content-Type: application/json

{
    "name": "John Doe",
    "email": "john@example.com",
    "password": "password123",
    "password_confirmation": "password123"
}
```

**Response:**

```
{
    "message": "User registered successfully",
    "data": {
        "token": "1|xxxxxxxxxxxx",
        "token_type": "Bearer",
        "user": {
            "id": 1,
            "name": "John Doe",
            "email": "john@example.com",
            "created_at": "2024-01-01T00:00:00.000000Z"
        }
    }
}
```

#### Login

[](#login)

```
POST /api/auth/login
Content-Type: application/json

{
    "login": "john@example.com", // Can be email or username ...
    "password": "password123"
}
```

**Response:**

```
{
    "message": "Login successful",
    "data": {
        "token": "1|xxxxxxxxxxxx",
        "token_type": "Bearer",
        "user": {
            "id": 1,
            "name": "John Doe",
            "email": "john@example.com"
        }
    }
}
```

### Login Configuration (Dynamic Identification)

[](#login-configuration-dynamic-identification)

- You can allow users to log in using different fields (e.g., either email or username).

```
'login' => [
    'fields' => [
        'login' => ['required', 'string'], // The input field name from frontend
        'password' => ['required', 'string'],
    ],
    // The database columns to search for the user
    'search_columns' => ['email',],
],
```

#### Forgot Password

[](#forgot-password)

```
POST /api/auth/forgot-password
Content-Type: application/json

{
    "email": "john@example.com"
}
```

#### Reset Password

[](#reset-password)

```
POST /api/auth/reset-password
Content-Type: application/json

{
    "token": "reset_token_here",
    "email": "john@example.com",
    "password": "newpassword123",
    "password_confirmation": "newpassword123"
}
```

### Protected Endpoints (Require Authentication)

[](#protected-endpoints-require-authentication)

All protected endpoints require the `Authorization` header:

```
Authorization: Bearer {token}
```

#### Get Profile

[](#get-profile)

```
GET /api/auth/profile
Authorization: Bearer {token}
```

**Response:**

```
{
    "message": "Profile retrieved successfully",
    "data": {
        "user": {
            "id": 1,
            "name": "John Doe",
            "email": "john@example.com",
            "email_verified_at": "2024-01-01T00:00:00.000000Z"
        }
    }
}
```

#### Refresh Token

[](#refresh-token)

```
POST /api/auth/refresh-token
Authorization: Bearer {token}
```

**Response:**

```
{
    "message": "Token refreshed successfully",
    "data": {
        "token": "2|xxxxxxxxxxxx",
        "token_type": "Bearer",
        "user": {  }
    }
}
```

#### Logout

[](#logout)

```
POST /api/auth/logout
Authorization: Bearer {token}
```

**Response:**

```
{
    "message": "Logged out successfully"
}
```

#### Send Email Verification

[](#send-email-verification)

```
POST /api/auth/email/verification-notification
Authorization: Bearer {token}
```

#### Verify Email

[](#verify-email)

```
GET /api/auth/email/verify/{id}/{hash}
```

🔧 Customization
---------------

[](#-customization)

### Adding Custom Fields to Registration

[](#adding-custom-fields-to-registration)

You can easily add custom fields to the registration process by adding them to the validation configuration. The package will automatically:

1. Validate the fields during registration
2. Save them to the database
3. Include them in API responses

**Example: Adding a phone number field**

1. Update your `config/api-auth.php`:

```
'validation' => [
    'name' => ['required', 'string', 'max:255'],
    'email' => ['required', 'string', 'email', 'max:255'],
    'password' => ['required', 'string'],
    'phone' => ['nullable', 'string', 'max:20'], // Add your custom field
    'username' => ['required', 'string', 'max:255', 'unique:users,username'],
],
```

2. Make sure your User model's `$fillable` array includes the new field:

```
protected $fillable = [
    'name',
    'email',
    'password',
    'phone',      // Add your custom field
    'username',   // Add your custom field
];
```

3. The field will now be automatically:
    - Validated during registration
    - Saved to the database
    - Included in API responses

**Example Registration Request:**

```
{
    "name": "John Doe",
    "email": "john@example.com",
    "password": "password123",
    "password_confirmation": "password123",
    "phone": "+1234567890",
    "username": "johndoe"
}
```

### Customizing Validation Rules

[](#customizing-validation-rules)

Edit `config/api-auth.php`:

```
'validation' => [
    'name' => ['required', 'string', 'max:255'],
    'email' => ['required', 'string', 'email', 'max:255'],
    'password' => ['required', 'string', 'min:12'], // Customize password rules
],
```

**Note:**

- The `email` field automatically gets a `unique` rule for registration
- The `password` field automatically gets `min_length` and `confirmed` rules based on config
- All other fields use the rules you specify exactly as configured

### Extending Services

[](#extending-services)

You can extend the services by binding your own implementations in a service provider:

```
use Martin6363\ApiAuth\Services\v1\AuthService;

$this->app->bind(AuthService::class, function ($app) {
    return new CustomAuthService();
});
```

### Customizing Routes

[](#customizing-routes)

You can disable specific routes in the configuration:

```
'routes' => [
    'enabled' => [
        'register' => false,  // Disable registration
        'login' => true,
        // ...
    ],
],
```

Or modify the route prefix:

```
'routes' => [
    'prefix' => 'api/v1/auth',  // Custom prefix
],
```

🛡️ Security Features
--------------------

[](#️-security-features)

- **Rate Limiting**: Prevents brute force attacks
- **Password Hashing**: Uses Laravel's secure password hashing
- **Token Revocation**: Tokens are revoked on password reset
- **Email Verification**: Optional email verification for new users
- **CSRF Protection**: Built-in CSRF protection for web routes

🧪 Testing
---------

[](#-testing)

The package includes test examples. Run tests with:

```
php artisan test
```

Or with Pest:

```
./vendor/bin/pest
```

Publish Logic
-------------

[](#publish-logic)

- \[!IMPORTANT\] Most of the package's behavior is controlled via the config/api-auth.php file. You should only publish and modify these files if you need to implement custom logic that cannot be achieved through configuration.

```
php artisan vendor:publish --tag=api-auth-logic ## Published controllers, services, and other logic files to your app for customization.
```

```
php artisan vendor:publish --tag=api-auth-config      # Configuration file
php artisan vendor:publish --tag=api-auth-lang        # Language/Translation files
php artisan vendor:publish --tag=api-auth-controllers # Authentication Controllers
php artisan vendor:publish --tag=api-auth-services    # Business logic services
php artisan vendor:publish --tag=api-auth-requests    # Validation/Form Requests
php artisan vendor:publish --tag=api-auth-resources   # API User Resources
php artisan vendor:publish --tag=api-auth-notifications # Email & System Notifications
```

📝 License
---------

[](#-license)

This package is open-sourced software licensed under the [MIT license](LICENSE.md).

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

📧 Support
---------

[](#-support)

For issues, questions, or contributions, please open an issue on the GitHub repository.

🙏 Credits
---------

[](#-credits)

Built with ❤️ for the Laravel community.

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance82

Actively maintained with recent releases

Popularity5

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~4 days

Total

7

Last Release

95d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/06a6e4a4e2e61ddef1bbfa6ee9b90c9bbf913fc9a15f532a4eb9bf8fa1147a19?d=identicon)[Martin6363](/maintainers/Martin6363)

---

Top Contributors

[![Martin6363](https://avatars.githubusercontent.com/u/134797897?v=4)](https://github.com/Martin6363 "Martin6363 (19 commits)")

---

Tags

apiapi-authapi-authenticationauthenticationlarave-12laravellaravel-12-api-authphpsanctumapilaravelauthAuthenticationtokenlaravel-packagesanctumjwt-alternative

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/martin6363-laravel-api-auth/health.svg)

```
[![Health](https://phpackages.com/badges/martin6363-laravel-api-auth/health.svg)](https://phpackages.com/packages/martin6363-laravel-api-auth)
```

###  Alternatives

[lab404/laravel-impersonate

Laravel Impersonate is a plugin that allows to you to authenticate as your users.

2.3k16.4M48](/packages/lab404-laravel-impersonate)[hasinhayder/tyro

Tyro - The ultimate Authentication, Authorization, and Role &amp; Privilege Management solution for Laravel 12 &amp; 13

6712.1k2](/packages/hasinhayder-tyro)[erjanmx/laravel-api-auth

Dead simple Laravel api authorization middleware

2024.5k](/packages/erjanmx-laravel-api-auth)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
