Sanctum API Registration Laravel

User
How to register api using santctum in laravel 11 when not api.php file provided
Assistant
In Laravel 11, the `api.php` file is no longer provided by default. However, you can still register API routes for Sanctum by defining them inside the `routes/web.php` file or by creating a separate file for API routes.

### **Steps to Register API Routes with Sanctum in Laravel 11**

#### **1. Create an API Routes File (Optional)**
Since `api.php` is not created by default in Laravel 11, you can manually create it inside the `routes` folder.

– Create a new file:

routes/api.php

– Add the following content:

<?php

  use IlluminateSupportFacadesRoute;
  use AppHttpControllersAuthController;

  Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
      return $request->user();
  });

  Route::post('/login', [AuthController::class, 'login']);
  Route::post('/register', [AuthController::class, 'register']);
  Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth:sanctum');

#### **2. Load `api.php` in `routes/web.php`**
Since Laravel 11 does not automatically load `api.php`, you need to include it in `routes/web.php` manually:

require __DIR__.'/api.php';

#### **3. Configure Sanctum Middleware in `Kernel.php`**
Make sure the Sanctum middleware is set up in `app/Http/Kernel.php`:

protected $middlewareAliases = [
      'auth:sanctum' => LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
  ];

#### **4. Install and Configure Sanctum**
If you haven't installed Sanctum yet, run:

composer require laravel/sanctum

Then, publish the Sanctum configuration:

php artisan vendor:publish --provider="LaravelSanctumSanctumServiceProvider"

Run migrations:

php artisan migrate

#### **5. Add Sanctum Trait in `User.php`**
In `app/Models/User.php`, add:

use LaravelSanctumHasApiTokens;

  class User extends Authenticatable
  {
      use HasApiTokens, HasFactory, Notifiable;
  }

#### **6. Test API**
– Use Postman or a tool like cURL to send requests.
– For protected routes, send the `Authorization: Bearer ` header.

This setup will allow Laravel 11 to handle API routes with Sanctum authentication even without the default `api.php` file. ๐Ÿš€

Leave a Comment

Your email address will not be published. Required fields are marked *