Laravel 13 API Routing with a Custom Domain
Laravel 13 does not include the API route file in a fresh project by default. If you want to build an API backend and bind its routes to a specific domain, you can initialize API routing and configure domain restrictions directly in routes/api.php.
1. Install API Routing
Run the following command from your Laravel project directory:
php artisan install:api
This command creates routes/api.php, installs Laravel Sanctum, and registers API routing in bootstrap/app.php.
If you are using Docker, execute it inside the PHP container:
docker exec -it -w /var/www/html <php-container-name> php artisan install:api
Replace /var/www/html with your actual Laravel project directory.
2. Configure the API Domain
You can use Route::domain() to group API routes under a specific domain.
First, add the domain to your .env file:
API_DOMAIN=api.example.com
Expose this value through config/app.php:
'api_domain' => env('API_DOMAIN', 'api.example.com'),
Then configure routes/api.php:
<?php
use Illuminate\Support\Facades\Route;
Route::domain(config('app.api_domain'))->group(function () {
Route::get('/ping', function () {
return response()->json([
'status' => 'ok',
]);
});
});
This keeps the domain configuration separate from your route definitions and works better with Laravel’s configuration caching.
3. Remove the Default API Prefix (Optional)
Laravel normally registers API routes with the /api prefix.
If you want the endpoint to be:
https://api.example.com/ping
instead of:
https://api.example.com/api/ping
you can configure the API prefix in bootstrap/app.php:
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
apiPrefix: '',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
4. Verify the Routes
Run:
php artisan route:list
Check the domain and URI columns to confirm that the routes are registered correctly.
Also ensure your Nginx or reverse proxy forwards the original host header to Laravel. Otherwise, Laravel may not receive the domain required for route matching.
Conclusion
Laravel 13 allows you to organize API routes directly in routes/api.php and restrict them to a custom domain with Route::domain().
For Docker deployments, keep the project working directory and domain configuration consistent across environments.
