Quickly create Laravel API authentication with Sanctum. Below shows how to setup a Laravel project API with authentication.
In this article we will setup a fresh Laravel project with API authentication and test the registration, login and profile pages with Postman.
First create a project.
laravel new example-app
By default there is no routes files and required database table for run a API. Run below command to create API routes file, other required tables and files.
php artisan install:api
Now add HasApiTokens trait to User model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasFactory, Notifiable, HasApiTokens;
// ..... rest of the code
Create controller to handle Authentication
php artisan make:controller APIAutheticationController
Open created controller and add below code to it.
- User registration.
- User login
- View user profile
- User logout
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class APIAuthenticationController extends Controller
{
//User registration with Sanctum
public function register(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|min:6',
]);
$user = User::create([
'name' => $validated['name'],
'email' => $validated['email'],
'password' => bcrypt($validated['password']),
]);
return response()->json(['message' => 'User registered'], 201);
}
//User login with santum token
public function login(Request $request)
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required'],
]);
if (!Auth::attempt($credentials)) {
return response()->json(['message' => 'Invalid login details'], 401);
}
$user = Auth::user();
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
//View user profile information
public function profile(Request $request)
{
return response()->json($request->user());
}
public function logout(Request $request)
{
$request->user()->currentAccessToken()->delete();
return response()->json(['message' => 'Logged out']);
}
}
Now add API routes to api.php file.
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\APIAuthenticationController;
Route::post('/login',[APIAuthenticationController::class,'login']);
Route::post('/logout',[APIAuthenticationController::class,'logout']);
Route::post('/register',[APIAuthenticationController::class,'register']);
Route::get('/user',[APIAuthenticationController::class,'profile'])->middleware('auth:sanctum');
middleware(‘auth:sanctum’) – This middleware ensures the the correct user is requesting information by providing the correct token.
Test the application using Postman
Every request you made to API should have the header “Accept: application/json” like below picture. Without that header you will not receive JSON response or validate errors on the controller.

Register
Create a POST request and add raw data to body and send a post request to http://localhost:8000/api/register
{
"name":"admin",
"email": "admin@gmail.com",
"password":"pass123"
}
Login
Send a post request to – http://localhost:8000/api/login and add body data
{
"email": "admin@gmail.com",
"password": "pass123"
}
You will receive a response like below.
{
"access_token": "4|iz6dcxbsiKQ9Qu7FxAP7YwzdLbmgSXqjVxoHtWXo93f77b50",
"token_type": "Bearer"
}
copy the access_token value.
View Profile
- Create a Get request to http://localhost:8000/api/user.
- Select Authorization tab and select “Bearer Token” as the Auth type.
- Paste above bearer token receive after login in the token input field.
Now you will see logged in user information in the response.