A secure, fast Laravel API comes down to eight habits: choose the right authentication (Sanctum or Passport), rate limit every route, validate all input with Form Requests, shape responses with API Resources, remove N+1 queries, cache deliberately, move slow work to queues, and run and monitor the API properly in production.
None of these are truly secret; they are in the official documentation. But they are often skipped under deadline pressure, and that is where data leaks and slow endpoints come from. This guide shows each one with short code examples for Laravel 13, the current release at the time of writing (see the Laravel release notes). Most examples also work on Laravel 11 and 12.
1. Pick the right authentication: Sanctum or Passport
Laravel has two first-party options. Sanctum is the default for most APIs: cookie-based sessions for your own single-page app and simple API tokens for mobile apps and scripts. Passport is a full OAuth2 server, which you only need when third parties must sign in your users and act on their behalf.
| Use case | Choose | Why |
|---|---|---|
| Your own SPA on the same top-level domain | Sanctum (SPA mode) | Session cookies with CSRF protection; no tokens stored in the browser |
| Your own mobile app | Sanctum (API tokens) | One token per device, revocable, with abilities |
| Server-to-server or personal access tokens | Sanctum (API tokens) | Simple, hashed tokens with scopes |
| Third-party apps acting for your users | Passport | Full OAuth2 flows, clients and scopes |
Install Sanctum with php artisan install:api, then issue tokens with only the abilities each client needs:
// Issue a token limited to reading orders, expiring in 30 days
$token = $user->createToken('mobile-app', ['orders:read'], now()->addDays(30));
return ['token' => $token->plainTextToken];
// routes/api.php: require a valid token with that ability
Route::get('/orders', [OrderController::class, 'index'])
->middleware(['auth:sanctum', 'abilities:orders:read']);
Two details matter. The abilities and ability middleware aliases must be registered in bootstrap/app.php (they map to Sanctum’s CheckAbilities and CheckForAnyAbility classes). And Sanctum tokens never expire by default, so set the expiration option in config/sanctum.php or pass an expiry when you create each token, then schedule sanctum:prune-expired to clean up old tokens.
Authentication tells you who is calling; it does not decide what they may do. Check ownership on every record with policies, for example Gate::authorize('update', $order). Broken object-level authorisation, where a user can read another user’s record by changing an ID, is the first risk on the OWASP API Security Top 10.
2. Rate limit per user and per route
Rate limiting protects you from brute-force logins, scraping and runaway clients. Define named limiters in the boot method of AppServiceProvider and attach them with the throttle middleware (see rate limiting):
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
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->input('email').'|'.$request->ip());
});
}
// routes/api.php
Route::post('/login', LoginController::class)->middleware('throttle:login');
Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
// ...
});
Use Redis as the cache store so limits are shared across all servers. Laravel returns HTTP 429 with Retry-After headers when a limit is hit, so well-behaved clients can back off.
3. Validate everything with Form Requests
Never trust input, and never pass $request->all() to a model. A Form Request keeps validation and authorisation out of your controller and returns a 422 JSON error automatically for API requests:
// php artisan make:request StoreOrderRequest
class StoreOrderRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()->can('create', Order::class);
}
public function rules(): array
{
return [
'product_id' => ['required', 'integer', 'exists:products,id'],
'quantity' => ['required', 'integer', 'min:1', 'max:100'],
'notes' => ['nullable', 'string', 'max:500'],
];
}
}
// Controller: only validated fields reach the database
public function store(StoreOrderRequest $request)
{
$order = $request->user()->orders()->create($request->validated());
return new OrderResource($order);
}
Combine this with $fillable on your models so fields such as is_admin or price can never be mass-assigned from a request.
Free resource
Upgrade and patching checklist
Want this applied to your project? Our engineers will send it with notes for your stack.
4. Shape responses with API Resources
Returning a model directly sends every column, including ones you add later. API Resources define exactly what leaves your server and keep the response format stable when the database changes:
class OrderResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'status' => $this->status,
'total' => $this->total,
'items' => OrderItemResource::collection($this->whenLoaded('items')),
'created_at' => $this->created_at->toIso8601String(),
];
}
}
// Always paginate lists
return OrderResource::collection(
Order::with('items')->latest()->paginate(25)
);
whenLoaded() includes a relationship only if you eager loaded it, so a resource never triggers surprise queries. If your clients expect the JSON:API format, Laravel 13 adds first-party JSON:API resources with sparse fieldsets and relationship includes.
5. Remove N+1 queries and index what you filter
The most common cause of a slow Laravel API is the N+1 problem: one query for a list, then one more query for each item’s relationship. Eager load with with(), and make Laravel throw an error whenever lazy loading happens outside production:
// AppServiceProvider::boot()
use Illuminate\Database\Eloquent\Model;
Model::preventLazyLoading(! $this->app->isProduction());
// Two queries instead of 1 + N, and only the columns you need
$orders = Order::with('customer:id,name')
->select('id', 'customer_id', 'status', 'total')
->where('status', 'paid')
->paginate(25);
Then add database indexes on the columns you filter, join and sort on (foreign keys, status, created_at), and use chunk() or lazy() for exports and imports. Laravel also offers Model::automaticallyEagerLoadRelationships(), but explicit eager loading keeps queries easier to read and review. See eager loading in the docs.
6. Cache deliberately, at deploy time and at data level
First, cache the framework itself. Run php artisan optimize in your deployment pipeline: it caches configuration, events, routes and views in one step. After config:cache, call env() only inside config files, because the .env file is no longer loaded.
Second, cache expensive data in Redis with a clear key and lifetime, and clear it when the data changes:
// Cache for 10 minutes
$products = Cache::remember('products:featured', 600, function () {
return Product::where('featured', true)->get();
});
// Clear it when a product changes
Cache::forget('products:featured');
Cache public, read-heavy data; be careful with anything user-specific, and include the user or tenant ID in the key when you do. Stale or cross-user cached data is a security bug, not just a performance one. Read more in the cache documentation.
7. Move slow work to queues
An API response should not wait for emails, webhooks, PDF generation, image processing or AI calls. Dispatch them to a queue and return immediately, typically with HTTP 202 for long tasks:
// php artisan make:job SendOrderConfirmation
class SendOrderConfirmation implements ShouldQueue
{
use Queueable;
public $tries = 3;
public $backoff = [10, 60, 300];
public function __construct(public Order $order) {}
public function handle(): void
{
Mail::to($this->order->customer)->send(new OrderConfirmed($this->order));
}
}
// In the controller
SendOrderConfirmation::dispatch($order);
Use Redis or Amazon SQS in production, run workers under a process monitor, and use Horizon to watch Redis queues and failed jobs. Laravel 13 also lets you declare retries, back-off and timeouts as attributes on the job class and route job classes to queues centrally with Queue::route(). Remember to reload workers after each deployment so they run the new code.
8. Run it fast and watch it: Octane and monitoring
Laravel Octane serves your API with FrankenPHP, Swoole, Open Swoole or RoadRunner. It boots the application once and keeps it in memory, which removes the framework boot cost from every request:
composer require laravel/octane
php artisan octane:install
php artisan octane:start --server=frankenphp --workers=4
The trade-off: because the app stays in memory, anything stored in singletons or static properties survives between requests. Do not inject the request, container or config into singleton constructors, avoid static arrays that grow, and test carefully before switching an older codebase.
Then make problems visible. Use Laravel Pulse or Nightwatch for slow queries, slow endpoints and exceptions in production, Telescope during local development, and the built-in /up health route for your load balancer. Log failed logins, authorisation failures and 429 responses so you can spot abuse. Keep APP_DEBUG=false in production; the Laravel docs warn that debug mode can expose configuration values to users.
Bonus: version your API from day one
Prefix routes with a version (/api/v1/...) using a route group, keep resources per version, and announce deprecations with a clear timeline. Mobile apps in particular stay installed for months, so old clients must keep working while new ones move on.
Laravel API security and performance checklist
| Area | Check |
|---|---|
| Authentication | Sanctum or Passport; tokens scoped with abilities and set to expire |
| Authorisation | Policy check on every record a user reads or changes |
| Input | Form Requests on every write; $fillable on every model |
| Output | API Resources only; no raw models; paginated lists |
| Abuse | Named rate limiters on login, writes and public endpoints |
| Database | Eager loading, lazy loading prevented in development, indexes on filter columns |
| Caching | php artisan optimize on deploy; Redis cache with clear keys and invalidation |
| Background work | Queues with retries and failed-job alerts; workers reloaded on deploy |
| Runtime | Supported Laravel and PHP versions; HTTPS only; APP_DEBUG=false |
| Visibility | Monitoring, health checks and security logging |
Frequently asked questions
Should I use Sanctum or Passport for a Laravel API?
Use Sanctum for your own SPA, mobile app or simple API tokens. Use Passport only when you need full OAuth2, for example when third-party apps act on behalf of your users.
How do I rate limit a Laravel API?
Define named limiters with RateLimiter::for() in AppServiceProvider, keyed by user ID or IP address, and attach them to routes with the throttle middleware. Use Redis so limits apply across all servers.
Do Sanctum tokens expire?
Not by default. Set the expiration value in the Sanctum config or pass an expiry date to createToken(), and schedule sanctum:prune-expired to remove old tokens.
Is Laravel Octane worth it for an API?
Often, for high-traffic APIs, because it removes the boot cost from each request. Fix N+1 queries, caching and queues first, and make sure your code does not keep request state in memory.
What is the most common Laravel API security mistake?
Missing record-level authorisation: checking that a user is logged in, but not that the order or file they request belongs to them. Add a policy check to every read and write.
Get your Laravel API reviewed or built at a fixed price
Vibidsoft builds and hardens Laravel APIs as fixed-price work, never by the hour. A fixed-price assessment (from $1,500, credited to the build) reviews your authentication, authorisation, rate limits, queries and hosting against this checklist and gives you a written fix list with a fixed quote. Larger builds run as milestone projects, each with acceptance criteria and its own fixed price.
See our Laravel development services and API integration services, browse more engineering guides, or book a free 20-minute call.
