Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save iammuttaqi/a2d8ceb1cb80a21802dd5e0690949e32 to your computer and use it in GitHub Desktop.

Select an option

Save iammuttaqi/a2d8ceb1cb80a21802dd5e0690949e32 to your computer and use it in GitHub Desktop.
Laravel API with Sanctum and Postman

Setting Up Laravel Sanctum Authentication with Laravel Breeze (API Scaffolding)

Follow these steps to implement authentication using Laravel Sanctum and Laravel Breeze with API scaffolding:

1. Install and Configure Laravel Breeze (API Mode)

Run the following command to install Laravel Breeze with API scaffolding:

composer require laravel/breeze --dev
php artisan breeze:install api
php artisan migrate

2. Add HasApiTokens Trait to the User Model

Open app/Models/User.php and add the HasApiTokens trait:

use Laravel\Sanctum\HasApiTokens;

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

3. Configure Postman for API Requests

To properly test Laravel Sanctum authentication, follow these setup steps in Postman:

  • Always pass the following header with API requests:

    Accept: application/json
    
  • Add a Pre-request Script to handle CSRF token retrieval:

    pm.sendRequest({
        url: 'http://localhost:8000/sanctum/csrf-cookie',
    }, function (err, res, {cookies}) {
        if (err) {
            console.log("Error fetching CSRF cookie:", err);
        } else {
            pm.collectionVariables.set('csrf', cookies.get('XSRF-TOKEN'));
        }
    });
  • Include the CSRF token in the request headers:

    X-XSRF-TOKEN: {{csrf}}
    

4. Generate and Return API Tokens After Login

Upon successful authentication, create and return an API token to the client:

return $user->createToken($request->device_name)->plainTextToken;

5. Use the Token for Authenticated Requests

For protected routes, include the token in the Authorization header:

Authorization: Bearer <your-token>

6. Revoke Tokens on Logout

When logging out, remove all tokens associated with the user:

$request->user()->tokens()->delete();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment