Most Top Paying Technologies in 2024
Read More
In Laravel 11, the framework has introduced a new php artisan install:api
command to streamline the setup of API-related components. This command automates the process of configuring your Laravel application for API development, including setting up routes, middleware, and other necessary files.
Let’s dive into how to use the php artisan install:api
command and what it does in Laravel 11.
php artisan install:api
When you run the php artisan install:api command, Laravel performs the following actions:
To set up your Laravel 11 application for API development, follow these steps:
cd your-laravel-project
php artisan install:api
This command will set up the necessary files and configurations for API development.
After running the command, verify the changes made by Laravel:
<?php
use Illuminate\Support\Facades\Route;
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
This route is protected by Laravel Sanctum and returns the authenticated user.
$app = Illuminate\Foundation\Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php', // API routes registered
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
// Middleware configuration
})
->withExceptions(function (Exceptions $exceptions) {
// Exception handling configuration
})->create();
Now that the API setup is complete, you can define your custom API routes in the routes/api.php file. For example:
use App\Http\Controllers\UserController;
Route::prefix('v1')->group(function () {
Route::get('/users', [UserController::class, 'index']);
Route::post('/users', [UserController::class, 'store']);
});
This example creates a route group with a v1 prefix, which is a common practice for versioning APIs.
You can test your API routes using tools like Postman or your browser. For example, if you defined a route like this:
Route::get('/users', function () {
return response()->json(['message' => 'List of users']);
});
You can access it by navigating to:
http://your-app-url/api/v1/users
If everything is set up correctly, you should see the JSON response:
{
"message": "List of users"
}
If you need API authentication, Laravel Sanctum is the recommended package. You can install it by running:
php artisan install:api --sanctum
This command will:
The php artisan install:api command in Laravel 11 simplifies the process of setting up your application for API development. It automates the creation of API routes, middleware configuration, and optional authentication setup using Laravel Sanctum.
By following this guide, you can quickly get started with building robust and scalable APIs in Laravel 11. Happy coding!
https://www.interviewsolutionshub.com/blog/laravel-sanctum-vs-passport-choosing-the-right-authentication-tool
Recent posts form our Blog
0 Comments
Like 0