Free 20-minute strategy call with a senior engineer: AI, payments, eLearning or custom software
Engineering

How to Build Secure and Reliable APIs with Laravel

How to Build Secure and Reliable APIs with Laravel

In short

Build secure Laravel APIs in Laravel 11+: Sanctum or Passport, policies, rate limiting, Form Requests, API Resources, CORS, testing and a checklist.

APIs connect your web app, mobile apps and partners to your data, which makes them a prime target for attackers. Laravel gives you excellent building blocks for secure and reliable APIs: authentication with Sanctum or Passport, authorisation with policies, validation, rate limiting, API resources and testing. This guide shows how to use them in a modern Laravel application (Laravel 11 and later), together with the security practices that keep APIs safe in production.

Quick answer: run php artisan install:api to add API routes and Laravel Sanctum, protect routes with auth:sanctum, authorise every action with policies or gates, validate input with Form Requests, return data through API Resources (never raw models), apply rate limiting, use HTTPS and strict CORS, log and monitor requests, and cover your endpoints with feature tests.

1. Why Laravel for API development

  • Expressive routing, middleware and controllers
  • First-party authentication (Sanctum and Passport)
  • Built-in validation, rate limiting and API resources
  • Eloquent ORM with protection against SQL injection when used properly
  • Queues, caching and events for reliable, scalable APIs
  • Excellent testing tools (Pest or PHPUnit)

2. Set up an API project

composer create-project laravel/laravel api-project
cd api-project
php artisan install:api

install:api creates routes/api.php, installs Laravel Sanctum and publishes its migration. Configure your database and other secrets in .env, which must never be committed to version control.

In Laravel 11 and later there is no app/Http/Kernel.php; middleware is configured in bootstrap/app.php.

3. Choose the right authentication

OptionBest forHow it works
Sanctum API tokensMobile apps, third-party scripts, simple token APIsPersonal access tokens with abilities (scopes)
Sanctum SPA authenticationYour own single-page app on the same top-level domainCookie-based session authentication with CSRF protection
PassportFull OAuth 2.0 server for third-party clientsAuthorization code, client credentials and other grants
External identity providerEnterprise SSO (Auth0, Entra ID, Okta, Cognito)Validate JWT access tokens issued by the provider

Read our detailed comparison of Laravel Sanctum vs Passport.

Issuing a Sanctum token with abilities

// app/Models/User.php
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
}
// routes/api.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use App\Models\User;

Route::post('/tokens', function (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.']]);
    }

    return ['token' => $user->createToken($request->device_name, ['orders:read'])->plainTextToken];
})->middleware('throttle:login');

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/user', fn (Request $request) => $request->user());
    Route::apiResource('orders', OrderController::class);
});

Give tokens only the abilities they need, set an expiry in config/sanctum.php, and let users revoke tokens.

Free resource

Upgrade and patching checklist

Want this applied to your project? Our engineers will send it with notes for your stack.

Get it free

4. Authorise every request

Authentication tells you who the user is; authorisation decides what they may do. Broken object-level authorisation (users accessing other users’ records) is the most common API vulnerability.

// app/Policies/OrderPolicy.php
public function view(User $user, Order $order): bool
{
    return $user->id === $order->user_id;
}
// app/Http/Controllers/OrderController.php
public function show(Order $order)
{
    $this->authorize('view', $order);

    return new OrderResource($order);
}

Also scope queries to the current user or tenant, for example $request->user()->orders()->findOrFail($id).

5. Rate limiting and throttling

Define named rate limiters in a service provider:

// app/Providers/AppServiceProvider.php
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;

public function boot(): void
{
    RateLimiter::for('api', function (Request $request) {
        return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
    });

    RateLimiter::for('login', function (Request $request) {
        return Limit::perMinute(5)->by($request->ip());
    });
}

Apply them with ->middleware('throttle:api'). Clients that exceed the limit receive HTTP 429.

6. Validate all input with Form Requests

php artisan make:request StoreOrderRequest
public function rules(): array
{
    return [
        'product_id' => ['required', 'integer', 'exists:products,id'],
        'quantity' => ['required', 'integer', 'min:1', 'max:100'],
        'notes' => ['nullable', 'string', 'max:500'],
    ];
}

Use only validated data ($request->validated()) and define $fillable on models to prevent mass assignment.

7. Return data with API Resources

php artisan make:resource OrderResource
public function toArray(Request $request): array
{
    return [
        'id' => $this->id,
        'status' => $this->status,
        'total' => $this->total,
        'created_at' => $this->created_at->toIso8601String(),
    ];
}

Resources control exactly which fields leave your API, so internal columns and sensitive data are never exposed by accident.

8. Consistent, safe error handling

  • Set APP_DEBUG=false in production so stack traces are never shown.
  • Return JSON errors with correct HTTP status codes (401, 403, 404, 422, 429, 500).
  • Customise exception rendering in bootstrap/app.php with withExceptions() for a consistent error format.
  • Log errors with context, but never log passwords, tokens or full card numbers.

9. Transport and browser security

  • Serve the API only over HTTPS, with HSTS.
  • Configure CORS in config/cors.php to allow only your trusted front-end origins.
  • Keep secrets in environment variables or a secrets manager, and rotate them.
  • Add security headers at the web server or with middleware.

10. Reliability: queues, caching and idempotency

  • Move slow work (emails, PDFs, third-party calls) to queues.
  • Cache expensive reads with Redis.
  • Support idempotency keys for payment-style endpoints so retries do not create duplicates.
  • Version your API (for example /api/v1/) and deprecate old versions with notice.
  • Use database transactions for multi-step writes.

11. Test your API

// tests/Feature/OrderApiTest.php (Pest)
it('prevents users from viewing other users orders', function () {
    $owner = User::factory()->create();
    $other = User::factory()->create();
    $order = Order::factory()->for($owner)->create();

    Sanctum::actingAs($other, ['orders:read']);

    $this->getJson("/api/orders/{$order->id}")->assertForbidden();
});

Test authentication, authorisation, validation and rate limits as well as the happy path. Use Telescope locally and tools such as Pulse, Sentry or Nightwatch in production.

12. Production checklist

AreaCheck
AuthenticationSanctum or Passport, token abilities, expiry
AuthorisationPolicies on every resource, scoped queries
InputForm Requests, $fillable, file upload limits
OutputAPI Resources, no sensitive fields
Abuse protectionRate limits, login throttling
TransportHTTPS, HSTS, strict CORS
ErrorsAPP_DEBUG=false, consistent JSON errors
Dependenciescomposer audit and regular updates
MonitoringLogging, alerts and uptime checks
StandardsReview against the OWASP API Security Top 10

Frequently asked questions

Is Sanctum or Passport better for APIs? Sanctum suits most APIs for your own apps and simple tokens; Passport is for full OAuth 2.0 when third parties need delegated access.

How do I add API authentication in Laravel 11 or 12? Run php artisan install:api, add the HasApiTokens trait to your User model, and protect routes with auth:sanctum.

How do I stop users accessing other users’ data? Use policies or gates on every action and scope database queries to the authenticated user or tenant.

How do I rate limit a Laravel API? Define rate limiters with RateLimiter::for() and apply them with the throttle middleware.

See also our guide to building RESTful APIs with Laravel.

Partner with Vibidsoft for Laravel API development

Vibidsoft Pvt Ltd builds secure, well-tested Laravel APIs for web and mobile apps, SaaS platforms and integrations, and audits existing APIs against security best practices. See our Laravel development services or contact us.

Vibidsoft Engineering Team

Senior engineers who have shipped 450+ projects since 2014 across AI, payments, eCommerce, eLearning and custom software. Every guide is written and reviewed by the people who do the work.

Follow us on LinkedIn · About Vibidsoft

Next step

Talk to an engineer about Modernize & Rescue

Fixed-price upgrades for ageing PHP, Drupal, Magento or hybrid apps, with security patching and a care plan. from $5,000.

  • A 20-minute call with a senior engineer, not a salesperson
  • A written next-step plan within one business day
  • NDA on request
Book a call WhatsApp