In Laravel 11, API route management takes a slightly different approach compared to earlier versions. New projects lack a dedicated API route file by default, streamlining the setup for applications without public-facing APIs. But fret not! If your project demands an API, publishing the necessary file and setting up Laravel Sanctum for authentication is a breeze.
1. Install the API Package
Open your terminal and navigate to your Laravel project’s root directory. Run the following Artisan command:
php artisan install:api
What this command does:
`Creates the routes/api.php file, where your API routes will reside.
Installs Laravel Sanctum, a package offering token-based authentication for your API.
Generates relevant migrations for Sanctum.
Adds a configuration file (config/sanctum.php) for Sanctum settings.`
2. Define Your API Routes
With the routes/api.php file in place, you can start defining your API endpoints using Laravel’s routing mechanisms. Here’s an example:
<?php use Illuminate\Auth\Middleware\Authenticate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route; Route::get('/user', function (Request $request) { return $request->user();
})->middleware(Authenticate::using('sanctum'));
By following these steps, you’ve successfully published the API route file in your Laravel 11 application and laid the foundation for building secure and efficient API endpoints. This approach not only simplifies the initial setup but also ensures a well-structured and organized codebase for your project.
Discover more from Coursity
Subscribe to get the latest posts sent to your email.