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
| Option | Best for | How it works |
|---|---|---|
| Sanctum API tokens | Mobile apps, third-party scripts, simple token APIs | Personal access tokens with abilities (scopes) |
| Sanctum SPA authentication | Your own single-page app on the same top-level domain | Cookie-based session authentication with CSRF protection |
| Passport | Full OAuth 2.0 server for third-party clients | Authorization code, client credentials and other grants |
| External identity provider | Enterprise 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.
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=falsein 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.phpwithwithExceptions()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.phpto 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
| Area | Check |
|---|---|
| Authentication | Sanctum or Passport, token abilities, expiry |
| Authorisation | Policies on every resource, scoped queries |
| Input | Form Requests, $fillable, file upload limits |
| Output | API Resources, no sensitive fields |
| Abuse protection | Rate limits, login throttling |
| Transport | HTTPS, HSTS, strict CORS |
| Errors | APP_DEBUG=false, consistent JSON errors |
| Dependencies | composer audit and regular updates |
| Monitoring | Logging, alerts and uptime checks |
| Standards | Review 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.
