0
0
Laravelframework~30 mins

API authentication with Sanctum in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
API authentication with Sanctum
📖 Scenario: You are building a simple Laravel API that requires user authentication. You want to use Laravel Sanctum to protect your API routes so only authenticated users can access them.
🎯 Goal: Create a Laravel API with Sanctum authentication. You will set up the user model, configure Sanctum, create a login route to issue tokens, and protect an API route that returns user data.
📋 What You'll Learn
Create a users table with name, email, and password fields
Install and configure Laravel Sanctum
Create a login API route that issues a Sanctum token
Protect an API route to return authenticated user info
💡 Why This Matters
🌍 Real World
APIs often need secure authentication to protect user data. Laravel Sanctum provides a simple way to add token-based authentication to your API.
💼 Career
Understanding API authentication with Sanctum is essential for backend developers working with Laravel to build secure and scalable web services.
Progress0 / 4 steps
1
Create the users table migration
Create a migration file for the users table with columns id, name, email, password, and timestamps. Use Laravel's schema builder with Schema::create('users') and the appropriate column types.
Laravel
Need a hint?

Use Schema::create('users', function (Blueprint $table) { ... }) and add the columns inside the closure.

2
Configure Sanctum in config/sanctum.php
Add the Sanctum middleware \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class to the api middleware group in app/Http/Kernel.php. Also, publish Sanctum's configuration and migration files using php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider".
Laravel
Need a hint?

Open app/Http/Kernel.php and add the Sanctum middleware to the api group array.

Then run the vendor publish command in your terminal.

3
Create a login route that issues Sanctum tokens
In routes/api.php, create a POST route /login that accepts email and password. Use Auth::attempt() to verify credentials. If successful, return a Sanctum token created by $user->createToken('api-token')->plainTextToken. If not, return a 401 response.
Laravel
Need a hint?

Use Route::post('/login', function (Request $request) { ... }) and inside check credentials with Auth::attempt().

If successful, create a token with $user->createToken('api-token')->plainTextToken.

4
Protect an API route to return authenticated user info
In routes/api.php, create a GET route /user protected by the auth:sanctum middleware. Return the authenticated user using $request->user().
Laravel
Need a hint?

Use Route::middleware('auth:sanctum')->get('/user', function (Request $request) { ... }) and return the authenticated user.