Courses

How to Build Laravel 11 API From Scratch

Authentication with Laravel Sanctum and API Tokens

Summary of this lesson:
- Personal access tokens implementation
- Creating and managing API tokens
- Adding token abilities (permissions)

This lesson will look at Laravel API authentication with Laravel Sanctum and API tokens. To understand how it is used and in what situations, you should read the official documentation.

From the docs:

This feature is inspired by GitHub and other applications which issue "personal access tokens".

Every user of your system would have a personal access token, which they would pass when making API calls.


After creating a new Laravel project and running the migrations, we have a personal_access_tokens table.

Next, you need to create a token for the user in your application. It could be some action panel on your page, some action on login, or automatically done after registration.

But, to create a token, the HasApiTokens trait has to be added in a User Model. It should be done after the install:api artisan command was executed.

app/Models/User.php:

use Laravel\Sanctum\HasApiTokens;
 
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
use HasApiTokens;
 
// ...
}

Next, you must protect API routes using the auth:sanctum Middleware. It's the same Middleware we used in the previous lesson for the SPA applications.

routes/api.php:

Route::get('/user', function (Request $request) {
return $request->user();
})->middleware('auth:sanctum');
 
Route::apiResource('categories', \App\Http\Controllers\Api\CategoryController::class)
->middleware('auth:sanctum');
 
Route::get('products', [\App\Http\Controllers\Api\ProductController::class, 'index']);

Now, if we try to access categories without passing any token, we will receive...

The full lesson is only for Premium Members.
Want to access all 23 lessons of this course? (58 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord